newInstanceできないクラスを無理やりインスタンス化する
newInstanceで汎用的にインスタンス化できないクラスがあります。例えば以下のようなクラスです。
public class HardToCreate { public HardToCreate(int code) { if (code != 123456789) { throw new IllegalArgumentException(); } } public void hello() { System.out.println("Hello!"); } }
Sunの非公開パッケージを使うと、このようなクラスでも、コンストラクタをすっ飛ばして無理やりnewInstanceできます。XStreamのソースから知りました。
以下、インスタンス化の実行例です。
import java.lang.reflect.Constructor; import sun.reflect.ReflectionFactory; public class Test { public static void main(String[] args) throws Exception { HardToCreate obj = forceNewInstance(HardToCreate.class); obj.hello(); } @SuppressWarnings("unchecked") public static <T> T forceNewInstance(Class<T> type) throws Exception { ReflectionFactory factory = ReflectionFactory.getReflectionFactory(); Constructor<?> cons = Object.class.getDeclaredConstructor(new Class[0]); Constructor<?> specialCons = factory.newConstructorForSerialization( type, cons); return (T) specialCons.newInstance(new Object[0]); } }