简体   繁体   English

是否真的需要调用java.lang.Object构造函数?

[英]Is calling java.lang.Object constructor really necessary?

I've recently installed bytecode outline Eclipse plugin and discovered that my Test class 我最近安装了字节码大纲Eclipse插件并发现了我的Test类

public class Test {
}

calls java.lang.Object's constructor 调用java.lang.Object的构造函数

public class Test {
  public <init>()V
   L0
    LINENUMBER 15 L0
    ALOAD 0
    INVOKESPECIAL java/lang/Object.<init>()V
    RETURN
   L1
    LOCALVARIABLE this LTest; L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1
}

INVOKESPECIAL java/lang/Object.<init>() V means calling java.lang.Object's constructor INVOKESPECIAL java/lang/Object.<init>() V表示调用java.lang.Object的构造函数

Does it make any sense? 它有意义吗? Judging by java.lang.Object bytecode 通过java.lang.Object字节码来判断

  public <init>()V
   L0
    LINENUMBER 37 L0
    RETURN
    MAXSTACK = 0
    MAXLOCALS = 1

it's doing nothing. 它什么都不做。 Just returns. 回报。

It has to in order to satisfy section 4.9.2 of the JVM specification on structural constraints: 它必须满足结构约束的JVM规范的4.9.2节

Each instance initialization method (§2.9), except for the instance initialization method derived from the constructor of class Object, must call either another instance initialization method of this or an instance initialization method of its direct superclass super before its instance members are accessed. 除了从Object类的构造函数派生的实例初始化方法之外,每个实例初始化方法(第2.9节)必须在访问实例成员之前调用此实例的另一个实例初始化方法或其直接超类super的实例初始化方法。

Now the rule could be relaxed for classes which are direct subclasses of Object - but I doubt that it would have any benefit, and would be inelegant (IMO). 现在规则可以放宽Object直接子类 - 但我怀疑它会有任何好处,并且会不优雅(IMO)。 What if the Object constructor did perform some initialization in the future? 如果该Object的构造的确在未来进行一些初始化? Would you really want a spec which allowed you to bypass it? 你真的想要一个允许你绕过它的规范吗?

Java compiler should not treat java.lang.Object differently than any other base class that probably has more sophisticated default constructor. Java编译器不应该以不同于可能具有更复杂的默认构造函数的任何其他基类来处理java.lang.Object Therefore the constructor of base class must be executed from constructor of any subclass. 因此,基类的构造函数必须从任何子类的构造函数执行。 This byte code is also safe for future modifications of base class (including Object ): if one day somebody changes base class the code of subclass should not be re-compiled. 这个字节代码对于将来修改基类(包括Object )也是安全的:如果有一天有人更改基类,则不应重新编译子类的代码。

BTW changes in base class including Object are not so exotic: think about instrumentation packages. 包括Object在内的基类的BTW变化并不那么奇特:考虑一下仪器包。 If you want to instrument the JDK and for example count all created object you want to modify byte code of java.lang.Object . 如果要对JDK进行检测,例如计算所有已创建的对象,则需要修改java.lang.Object字节代码。 Now, if byte code does not contain invocation of Object constructor your instrumented code just will not run. 现在,如果字节代码不包含Object构造函数的调用,则您的检测代码将无法运行。

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

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