简体   繁体   English

在Java中创建数组时是否调用了Object构造函数?

[英]Is Object constructor called when creating an array in Java?

In Java, an array IS AN Object. 在Java中,数组是一个对象。 My question is... is an Object constructor called when new arrays is being created? 我的问题是......是在创建新数组时调用的Object构造函数吗? We would like to use this fact to instrument Object constructor with some extra bytecode which checks length of array being constructed. 我们希望使用这个事实来检测Object构造函数,并使用一些额外的字节码来检查正在构造的数组的长度。 Would that work? 那会有用吗?

Per the JVM spec : "Arrays are created and manipulated using a distinct set of instructions." 根据JVM规范 :“使用一组不同的指令创建和操作数组。” 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). 因此,虽然数组是对象的实例,但它们的初始化方式与其他对象的初始化方式相同(如果从该链接锚点向上滚动,则可以看到)。

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. 就Java语言规范而言,尽管两者都使用new关键字,但Class Instance Creation ExpressionsArray Creation Expressions是不同的表达形式,每种表达形式都有自己的规则。 The description of Array Creation Expressions does not mention calling a constructor. Array Creation Expressions的描述没有提到调用构造函数。

我不这么认为,因为你无法派生一个本机数组来覆盖构造函数

您可以使用字节代码操作将检查放在创建新数组的位置。

Nope. 不。 I found this on the AspectJ mailing list: http://dev.eclipse.org/mhonarc/lists/aspectj-users/msg02975.html . 我在AspectJ邮件列表中找到了这个: 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. 这将为您提供很多拦截和验证的机会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM