传递类类型作为参数以在 ArrayList 中使用? [英] Pass class type as parameter to use in ArrayList?
问题描述
我需要编写一个 java 方法,它接受一个类(不是一个对象),然后创建一个 ArrayList,该类作为数组中每个成员的元素.伪代码示例:
I need to write a java method which takes a class (not an object) and then creates an ArrayList with that class as the element of each member in the array. Pseudo-code example:
public void insertData(String className, String fileName) {
ArrayList<className> newList = new ArrayList<className>();
}
如何在 Java 中完成此操作?
How can I accomplish this in Java?
推荐答案
您可以使用 泛型方法
public <T> void insertData(Class<T> clazz, String fileName) {
List<T> newList = new ArrayList<>();
}
但是如果你应该使用这个契约insertData(String className, String fileName)
,你不能使用泛型,因为Java无法在编译时解析列表项的类型.
but if you should use this contract insertData(String className, String fileName)
, you cannot use generics because type of list item cannot be resolved in compile-time by Java.
在这种情况下,您可以根本不使用泛型,而是在将其放入列表之前使用反射来检查类型:
In this case you can don't use generics at all and use reflection to check type before you put it into list:
public void insertData(String className, String fileName) {
List newList = new ArrayList();
Class clazz;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e); // provide proper handling of ClassNotFoundException
}
Object a1 = getSomeObjectFromSomewhere();
if (clazz.isInstance(a1)) {
newList.add(a1);
}
// some additional code
}
但是如果没有类的信息,您只能使用 Object
,因为您无法在代码中将对象转换为 UnknownClass.
but without information of class you're able use just Object
because you cannot cast your object to UnknownClass in your code.
这篇关于传递类类型作为参数以在 ArrayList 中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!