Creating an instance of an unconstructed object

In Java, is there a way to separate the steps that occur when an object is created:

  • memory allocation
  • building an object

In other words, are there high-level constructors (perhaps using refection?) That accurately display the bytecode instructions new (memory allocation) and invokespecial (building an object).

No specific use, more like curiosity.

+6
source share
3 answers

No, there is no API in the JDK (reflection or otherwise). However, you can manipulate the byte code itself at runtime using libraries that do this. For example, http://asm.ow2.org/

+3
source
  sun.misc.Unsafe /** Allocate an instance but do not run any constructor. Initializes the class if it has not yet been. */ public native Object allocateInstance(Class cls) throws InstantiationException; ---- Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); Unsafe unsafe = (Unsafe) f.get(null); Integer integer = (Integer)unsafe.allocateInstance(Integer.class); System.out.println(integer); // prints "0" 

I don’t know how to make the second part - call the constructor on it.

+2
source

The JVM creates objects before they are passed to the constructor; if the constructor of the derived class throws an exception before binding to the constructor of the base class, I would expect the method of the Finalize derived class Finalize be run on the object without any part of the base constructor ever being executed.

0
source

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


All Articles