创建未构造的对象实例

时间:2013-06-09 19:05:03

标签: java bytecode

在Java中,有没有办法分离对象创建过程中发生的步骤:

  • 内存分配
  • 对象构建

换句话说,是否有高级构造(可能使用反射?)准确映射字节码指令new(内存分配)和invokespecial(对象构造)。

没有特别的用法,更像是一种好奇心。

3 个答案:

答案 0 :(得分:3)

不,JDK中没有API(反射或其他)。但是,您可以在运行时使用执行此操作的库来操作字节代码本身。例如,http://asm.ow2.org/

答案 1 :(得分:2)

     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"

不知道如何做第二部分 - 在其上调用构造函数。

答案 2 :(得分:0)

JVM在将对象赋予构造函数之前创建对象;如果派生类构造函数在链接到基类构造函数之前抛出异常,我希望派生类Finalize方法将在对象上运行,而基本构造函数的任何部分都没有运行。

相关问题