参见英文答案 > How to set the generic type of an ArrayList at runtime in java?????????????????????????????????????4个
如何实例化Java泛型对象,该对象仅接受类或参数给出的类型参数宾语?
例如:
通常,可以使用以下语法实例化Integer对象的ArrayList:
ArrayList foo = new ArrayList();
但是,给定一个Class诸如Integer.class之类的对象,怎么能创建一个类似的ArrayList?例如,我将如何做这样的事情(语法不正确):
ArrayList foo = new ArrayList();
我需要这个用于Java的非常不寻常的事情(创建一个开源工具,用于可视化用户提供的数据结构实例/他们编写的泛型类).以下是我将如何使用此代码的示例,该代码说明了我将获得的信息:
import java.util.ArrayList;
import java.util.List;
public class ArrayListFromClass {
// obviously this code does not work
public static void main(String[] args) {
Object givenObject = new Integer(4);
// I would not know it is Integer.class, a Class> object would be supplied by the user/ as a generic
Class> cls = givenObject.getClass();
List bar = new ArrayList();
// Where args[0] is "Integer.class"
List foo = new ArrayList();
// then I would be able to add to foo or bar with one or both of these techniques:
// printing givenObject.getClass() gives you java.lang.Integer, don't worry about the casting not working.
bar.add(cls.cast(givenObject));
Integer y = 6;
bar.add(y);
}
}