views:

633

answers:

4

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?

A: 

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

Fernando Miguélez
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ý
+3  A: 

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
Looks like constructor is not called after newarray :-(Thank you.
Peter Štibraný
A: 

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

Peter Lawrey
You mean by instrumenting every method in every class? (We wanted to avoid this.)
Peter Štibraný
A: 

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.

St3fan
Hello... it seems like something is missing in your first line.
Peter Štibraný