【发布时间】:2018-10-22 13:25:15
【问题描述】:
我正在编写代码,我必须将基类转换为派生类,其中我有一组由基类派生的泛型类型。
例如,我有 Base 和 Derived1、Derived2 并将它们放入 Class[]{Derived1.class, Derived2.class} 并将这个数组传递给类的构造函数。
在这个构造函数中,我必须创建这些派生类的实例,但我不知道该怎么做,因为我得到了 Class 和 Base 不兼容的信息。
这是我的代码示例
public abstract class Base {
public abstract Base create(String s);
}
public class Derived extends Base {
java.lang.Integer value;
private static Derived integer = new Derived();
public static Derived getInstance(){
return integer;
}
public Base create(String s) {
value = java.lang.Integer.parseInt(s);
return this;
}
}
public class Clazz {
Class<? extends Base> type;
ArrayList<Base> arrayList;
public Class<? extends Base> getType() {
return type;
}
}
public class AnotherClazz{
ArrayList<Clazz> clazzArrayList;
Class<? extends Base>[] types;
AnotherClazz(Class<? extends Base>[] args){
clazzArrayList = new ArrayList<>();
types = args; // assuming I pass 2 elements in array
String[] strings = new String[]{"1","2"};
for (int i=0; i<args.length; ++i){
if (types[i] instanceof Base){
// here i want to check validity of class
}
}
for (int i=0; i<strings.length; ++i){
clazzArrayList.get(i).arrayList.add(((types[i]) Base).getInstance().create(strings[i]));
//here i want to create instance of object from type assigned to specific column
}
}
感谢您的帮助。
【问题讨论】:
-
我在下面的评论中发布了代码
-
.add(((types[i]) Base)- 在这种情况下,Base是什么意思?我假设您只想使用types[i]并在其上调用构造函数(或任何getInstance()的意思 - 你是说Class中的newInstance(params)吗?)