这是代码:
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
?