Is Object constructor called when creating an array in Java?
Asked Answered
E

5

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?

Erudition answered 23/1, 2009 at 22:37 Comment(0)
I
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.

Interleave answered 15/6, 2014 at 15:57 Comment(0)
S
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).

Sensitive answered 23/1, 2009 at 22:54 Comment(1)
Looks like constructor is not called after newarray :-( Thank you.Davie
I
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.

Interleave answered 15/6, 2014 at 15:57 Comment(0)
O
0

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

Obscure answered 23/1, 2009 at 22:43 Comment(1)
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)Davie
K
0

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

Knecht answered 23/1, 2009 at 22:56 Comment(1)
You mean by instrumenting every method in every class? (We wanted to avoid this.)Davie
B
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.

Breastfeed answered 23/1, 2009 at 23:26 Comment(1)
Hello... it seems like something is missing in your first line.Davie

© 2022 - 2025 — McMap. All rights reserved.