指定されたクラスタイプのインスタンスを返すメソッドが必要です。提供されるタイプが、それらの「空の」インスタンスを作成できるように制限されていると仮定しましょう。たとえば、指定するString.class
と空の文字列Integer.class
が返され、を指定すると初期値がゼロの整数が返されます。しかし、(ボックス化された)プリミティブ型をその場で作成するにはどうすればよいですか?このような?
public Object newInstance(Class<?> type) {
if (!type.isPrimitive()) {
return type.newInstance(); // plus appropriate exception handling
} else {
// Now what?
if (type.equals(Integer.class) || type.equals(int.class)) {
return new Integer(0);
}
if (type.equals(Long.class) // etc....
}
}
考えられるすべてのプリミティブ型を反復処理する唯一の解決策ですか、それとももっと簡単な解決策がありますか?両方に注意してください
int.class.newInstance()
と
Integer.class.newInstance()
InstantiationException
(nullaryコンストラクターがないため)をスローします。