6

Java では、オブジェクトの作成中に発生するステップを分離する方法はありますか。

  • メモリ割り当て
  • オブジェクトの構築

言い換えれば、バイトコード命令new(メモリ割り当て)とinvokespecial(オブジェクト構築)を正確にマッピングする高レベルの構造(おそらくリフェクションを使用?)がありますか?

特に用法はなく、好奇心のようなものです。

4

3 に答える 3

3

いいえ、JDK にはこのための API (リフレクションまたはその他) はありません。ただし、それを行うライブラリを使用して、実行時にバイトコード自体を操作できます。たとえば、http://asm.ow2.org/

于 2013-06-09T19:14:12.907 に答える
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番目の部分を行う方法がわからない-コンストラクターを呼び出します。

于 2013-06-10T03:24:30.303 に答える