gpt4 book ai didi

java - 从存储在容器中的类构造对象

转载 作者:行者123 更新时间:2023-12-01 14:48:01 27 4
gpt4 key购买 nike

这是代码:

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

最佳答案

您的Class[]应该是Class<? extends Base>[] 。或者,使用 List<Class<? extends Base>> ,这不会导致泛型警告。

关于java - 从存储在容器中的类构造对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15207651/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com