我想在运行时使用反射获取集合的通用类型。
代码(JAVA):
Field collectionObject = object.getClass().getDeclaredField(
collectionField.getName());
//here I compare to see if a collection
if (Collection.class.isAssignableFrom(collectionObject.getType())) {
// here I have to use the generic type of the collection
// to see if it's from a specific type - in this case Persistable
if (Persistable.class.isAssignableFrom(GENERIC_TYPE_COLLECTION.class)) {
}
}
有没有办法在运行时在 java 中获取集合的泛型类型?在我的例子中,我需要集合泛型类型的 .class。
提前致谢!
最佳答案
Type erasure意味着有关对象的通用类型的信息在执行时根本不存在。
(链接指向 Angelika Langer 的 Java Generics FAQ 的相关部分,它几乎可以回答您可能提出的关于 Java 泛型的所有问题:)
但是,您并不真正对对象的类型感兴趣 - 您对字段的类型感兴趣。我误解了这个问题,虽然答案已被接受,但我希望通过现在修复它来弥补 :)
如果字段本身不使用类型参数,则可以这样做。例如:
import java.lang.reflect.*;
import java.util.*;
public class Test
{
public List<String> names;
public static void main(String [] args)
throws Exception // Just for simplicity!
{
Field field = Test.class.getDeclaredField("names");
ParameterizedType type = (ParameterizedType) field.getGenericType();
// List
System.out.println(type.getRawType());
// Just String in this case
for (Type typeArgument : type.getActualTypeArguments())
{
System.out.println(" " + typeArgument);
}
}
}
如果该字段属于类 T
字段为 List<T>
那么您必须知道实例的类型参数才能知道集合的类型参数。
虽然将其转换为您所需的代码有些棘手 - 您确实需要知道集合类的类型参数。例如,如果有人声明:
public class StringCollection implements Collection<String>
然后有一个类型为 StringCollection
的字段,该字段本身不会有任何类型参数。然后你需要检查 getGenericSuperType
和 getGenericInterfaces
递归直到找到你想要的。
虽然有可能,但要做到这一点确实不容易。如果我是你,我会尝试更改你的设计,这样你就不需要它了。
关于java - 在运行时指定通用集合类型参数(Java 反射),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1127923/