如何让 Java 方法返回任何类型的泛型列表? [英] How to have Java method return generic list of any type?
本文介绍了如何让 Java 方法返回任何类型的泛型列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个方法,它可以返回任何类型的 java.util.List
而无需进行任何类型转换:
I would like to write a method that would return a java.util.List
of any type without the need to typecast anything:
List<User> users = magicalListGetter(User.class);
List<Vehicle> vehicles = magicalListGetter(Vehicle.class);
List<String> strings = magicalListGetter(String.class);
方法签名会是什么样的?像这样的东西,也许(?):
What would the method signature look like? Something like this, perhaps(?):
public List<<?> ?> magicalListGetter(Class<?> clazz) {
List<?> list = doMagicalVooDooHere();
return list;
}
推荐答案
private Object actuallyT;
public <T> List<T> magicalListGetter(Class<T> klazz) {
List<T> list = new ArrayList<>();
list.add(klazz.cast(actuallyT));
try {
list.add(klazz.getConstructor().newInstance()); // If default constructor
} ...
return list;
}
也可以为方法提供泛型类型参数.您已经正确地推断出需要正确的类实例来创建事物(klazz.getConstructor().newInstance()
).
One can give a generic type parameter to a method too. You have correctly deduced that one needs the correct class instance, to create things (klazz.getConstructor().newInstance()
).
这篇关于如何让 Java 方法返回任何类型的泛型列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文