インターフェイス(A)と、それを実装したクラス(B,C)で、
クラスはデフォルトコンストラクターがある前提です。
インターフェイスの無いクラスで実現する場合は、
どんなクラスでもnewできてしまう危険があるのと、
個別にキャストする処理が必要になってしまうので、
可能であればインターフェイスを使うのをおすすめします。
`
// Java7以降の書き方
interface A {
// ...
}
class B implements A {
// ...
}
class C implements A {
// ...
}
class Sample {
static <T extends A> T newInstanceFromClassName(String fqcn) {
try {
@SuppressWarnings("unchecked")
Class<T> c = (Class<T>) Class.forName(fqcn);
return c.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
// TODO エラー処理
throw new IllegalArgumentException("class not found: " + fqcn, e);
}
}
public static void main(String[] args) {
A b = newInstanceFromClassName("sample.B");
A c = newInstanceFromClassName("sample.C");
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
`
2014/08/28 01:17