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"
2番目の部分を行う方法がわからない-コンストラクターを呼び出します。