When is a Java object fully initialized?

As you know, the object just allocated by the new byte is not initialized and, therefore, is not java.lang.Object . If I do a bytecode manipulation at runtime and pass this object to a method, the JVM will complain or even crash (because the β€œthing” I gave it is not java.lang.Object ).

So my question is when the objects are β€œcompletely” initialized, i.e. become java.lang.Object ? This is when the constructor ( <init> ):

  • is called?
  • coming back?
  • some time before his return?
  • calls java.lang.Object.<init> ?
  • some other time?
+5
source share
2 answers

From the point of view of any given <init> method, the value of this is considered initialized after the invokespecial call invokespecial , whether this call calls another <init> method in the same class or superclass.

Similarly, for objects created using the new command, they are considered initialized after using the invokespecial a <init> method.

Note that initialization tracking is local to the method. Bytecode verification is performed based on a method by a method, and each method only sees objects created in it and method calls. The fact that it is impossible to initialize this value in the constructor without calling another constructor ensures that it will ultimately be bound to the java.lang.Object constructor if it does not go or goes into an infinite loop.

+5
source

Here is the bytecode of the class method "Foo"

  public <init>()V L0 LINENUMBER 1 L0 ALOAD 0 INVOKESPECIAL java/lang/Object.<init> ()V RETURN L1 LOCALVARIABLE this LFooTest; L0 L1 0 MAXSTACK = 1 MAXLOCALS = 1 

when you try to create a new instance of Foo, there will be INVOKESPECIAL java / lang / Object. () V, and after that the object will be created on the memory heap, and the link in the stack will be returned and assigned to this. therefore, in my opinion, the answer to your question should be "after calling java.lang.Object.init ()"

0
source

Source: https://habr.com/ru/post/1275576/


All Articles