In Java, is there any way to separate the steps that happen during object creation:
In other words, are there high level constructs (maybe using refection?) that accurately map the bytecode instructions new
(memory allocation) and invokespecial
(object construction).
No particular usage, more like a curiosity thing.
No, there is no API (reflection or otherwise) for this in the JDK. You can however manipulate byte code itself, at runtime, using libraries that do that. For example, http://asm.ow2.org/
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"
don't know how to do the 2nd part - invoke constructor on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With