コードは次のとおりです。
import java.util.ArrayList;
import java.util.List;
public class Main {
public abstract static class Base {
}
public static class Derived1 extends Base {
}
public static class Derived2 extends Base {
}
public static <T> T createObject(Class<T> someClass) {
T a = null;
try {
a = someClass.newInstance();
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
}
return a;
}
public static void main(String[] args) {
Derived2 d2 = createObject(Derived2.class); // here it works
// here is some array with classes
Class[] someClasses = new Class[] { Derived1.class, Derived2.class };
// here is some list which should be filled with objects of these classes
List<? extends Base> l = new ArrayList();
// in this loop, the list should be filled with objects
for(Class c : someClasses) {
l.add(createObject<? extends Base>(c)); // ERROR: java: illegal start of expression
}
}
}
上記のコードのエラーは次の行にあります。
l.add(createObject<? extends Base>(c)); // ERROR: java: illegal start of expression
リストが配列内のクラスのオブジェクトで満たされるように、for
ループを正しく構築する方法とメソッドを正しく呼び出す方法は?createObject
l
someClasses