我正在尝试创建一个可以返回不同类型数据列表的方法。 type 参数用于标识需要处理并返回 getListedData(Class type) 的数据类型。我还编写了一个私有(private)方法 createList(Class type, List list, String flag) ,所有类型数据都可以使用它来创建列表。
代码正在执行我所期望的操作,但作为泛型的新手,我不确信这是最好的编写方式。有人能给我一些建议吗?特别是使用泛型与 LIst 和反射构造函数来创建对象实例。 (我使用它的原因是使该方法可重用于所有类型)。我对 Actor 阵容感到恼火:(
那些不同类型的类具有相同的结构。
public class TypeA {
private String propOne;
public TypeA(String propOne) {
super();
this.propOne = propOne;
}
public String getPropOne() {
return propOne;
}
public void setPropOne(String propOne) {
this.propOne = propOne;
}
}
public class TypeB {
private String propOne;
public TypeB(String propOne) {
super();
this.propOne = propOne;
}
public String getPropOne() {
return propOne;
}
public void setPropOne(String propOne) {
this.propOne = propOne;
}
}
将会有大量相同的结构化数据类型。
public class Test {
@SuppressWarnings("unchecked")
public static void main(String arg[]) throws SecurityException, IllegalArgumentException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException{
Test test = new Test();
List<TypeB> b = (List<TypeB>) test.getListedData(TypeB.class);
List<TypeA> a = (List<TypeA>) test.getListedData(TypeA.class);
//similar repeate.....
}
public <T> List<T> getListedData(Class<T> type) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException{
List<T> list = new ArrayList<T>();
String flag = "";
if(type.equals(TypeA.class)){
flag = "A";
createList(type, list, flag);
}else{
flag = "B";
createList(type, list, flag);
}
return list;
}
private <T> void createList(Class<T> type, List<T> list, String flag)
throws NoSuchMethodException, InstantiationException,
IllegalAccessException, InvocationTargetException {
for(int i=0; i<2; i++){
Constructor<?> ctor = type.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] {String.valueOf(i)});
list.add((T) object);
//do something with flag...
}
}
}
如有任何建议,我们将不胜感激。谢谢
最佳答案
最好避免出现案例。 您可以执行以下操作,或者也通过反射使用类的静态成员。
public <T> List<T> getListedData(Class<T> type) throws SecurityException,
NoSuchMethodException, IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException {
List<T> list = new ArrayList<>();
String flag = type.getSimpleName();
createList(type, list, flag);
return list;
}
private <T> void createList(Class<T> type, List<T> list, String flag)
throws NoSuchMethodException, InstantiationException,
IllegalAccessException, InvocationTargetException {
for (int i = 0; i < 2; i++) {
Constructor<?> ctor = type.getConstructor(String.class);
Object object = ctor.newInstance(new Object[]{String.valueOf(i)});
list.add((T) object);
//do something with flag...
}
}
关于java - 以参数化类型作为参数返回不同类型对象列表的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16219696/