9

In Java, an array IS AN Object. My question is... is an Object constructor called when new arrays is being created? We would like to use this fact to instrument Object constructor with some extra bytecode which checks length of array being constructed. Would that work?

Peter Štibraný
  • 32,463
  • 16
  • 90
  • 116

5 Answers5

6

Per the JVM spec: "Arrays are created and manipulated using a distinct set of instructions." So, while arrays are instances of Objects, they aren't initialized the same way that other objects are (which you can see if you scroll up from that link anchor).

kdgregory
  • 38,754
  • 10
  • 77
  • 102
1

As far as the Java Language Specification is concerned, although both use the new keyword, Class Instance Creation Expressions and Array Creation Expressions are different forms of expression, each with its own rules. The description of Array Creation Expressions does not mention calling a constructor.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
0

I don't think so because you can not derive a native array to overridethe constructor

Fernando Miguélez
  • 11,196
  • 6
  • 36
  • 54
  • I am not sure I understand. Can you elaborate please? (I don't want to override the constructor... I want to put extra bytecode there. Object( ) constructor is called on every object creation. As array is an object too, I expect that Object() is also called in this case) – Peter Štibraný Jan 23 '09 at 22:46
0

You can use byte code manipulation to place the check where ever a new array is created.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Nope. I found this on the AspectJ mailing list: http://dev.eclipse.org/mhonarc/lists/aspectj-users/msg02975.html.

You probably ask about arrays for a reason, but if you can, why not switch to the collection classes. That will give you lots of opportunity to intercept and do validations.

Peter Štibraný
  • 32,463
  • 16
  • 90
  • 116
Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88