在 Java 中,有没有办法分离对象创建过程中发生的步骤:
- 内存分配
- 对象构造
换句话说,是否存在精确映射字节码指令new
(内存分配)和invokespecial
(对象构造)的高级构造(可能使用反射?)。
没有特别的用法,更像是好奇的东西。
不,JDK 中没有用于此的 API(反射或其他)。但是,您可以在运行时使用执行此操作的库来操作字节码本身。例如,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"
不知道如何做第二部分 - 在上面调用构造函数。
JVM 在将对象提供给构造函数之前创建对象;如果派生类构造函数在链接到基类构造函数之前抛出异常,我希望派生类Finalize
方法将在对象上运行,而基构造函数的任何部分都不会运行。