Is Object constructor called when creating an array in Java?

流过昼夜 提交于 2019-12-01 15:16:31

问题


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?


回答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.




回答2:


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).




回答3:


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




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/474896/is-object-constructor-called-when-creating-an-array-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!