![](/img/trans.png)
[英]How to use Java reflection to check if ParameterizedType argument extends a specific class
[英]Java Reflection: How to obtain an instance of Class<T> from the ParameterizedType.getActualTypeArguments() array?
我想要做的是使用一个 Field 的通用 typearg
Type type = f.getGenericType();
if (type instanceof ParameterizedType) {
ParameterizedType ptype = (ParameterizedType) type;
// ...
Class<?> typearg0 = ??? // ptype.getActualTypeArguments()[0]
}
(其中f
是java.lang.Field
的一个实例)。 我需要Class<?>
的实例来执行Foo.class.isAssignableFrom(typearg0)
检查,它只需要Class<T>
es作为参数。 同时,我知道(或期望)说typearg0
也是参数化类型,因此存在矛盾: typearg0
不能同时是Class<?>
和ParameterizedType
,因为Class<?>
本身就是 class 和不实现ParameterizedType
。
我可以以任何其他方式实现isAssignableFrom()
检查吗? 或者我的目标通常是不可能实现的?
非常感谢!
编辑:
这是一个例子:
假设您期望Map<Foo, Set<Bar>>
类型的 Field,但您得到的只是java.lang.reflect.Field
实例。 现在,您不希望它精确匹配Map<Foo, Set<Bar>>
,您只希望各自的类型是Map
或Set
的实例。 这不是严格的规范检查,更像是“健全性检查”。 我会尝试这样的检查:
.getType()
)Map
是否可从字段类型分配.getGenericType()
)Foo
(这应该是完全匹配的)Set
是否可以从此嵌套类型分配ParameterizedType
并强制转换Bar
(这应该是完全匹配的)但是,我不知道如何达到 5 和/或 6。
(使用 java 11)
就像您对Map
所做的一样, Set
很可能是ParameterizedType
的一个实例,因此您可以检查它然后进行转换。
从那个ParameterizedType
(代表Set<Something>
),您可以使用getRawType
来获取Set
。 这也是一个Type
——但这应该可以安全地转换为Class
。 以防万一,您可以使用后备并使用其名称加载 class。
final Type valueType = mapType.getActualTypeArguments()[1];
final ParameterizedType pValueType = (ParameterizedType) valueType;
final Class<?> valueClass = pValueType.getRawType() instanceof Class ?
((Class<?>) pValueType.getRawType()) :
// Should be castable, but just in case it's not, fallback
getClass().getClassLoader().loadClass(
pValueType.getRawType().getTypeName()
);
if (Set.class.isAssignableFrom(valueClass)) { /* do something*/ }
这是一个完整的可运行示例。
class Foo {}
class Bar {}
interface MyValidMap extends Map<Foo, Set<Bar>> {}
public class Application {
public final HashMap<Foo, HashSet<Bar>> good = null;
public final Map<Foo, Set<Bar>> better = null;
public final String notAMap = null;
public final Map<String, Set<Bar>> badKey = null;
public final Map<Foo, List<String>> badValue = null;
public final Map<Foo, Set<String>> badSetElems = null;
public final MyValidMap noTypeParamMap = null;
public static void main(String[] args) throws Exception {
for (Field field : Application.class.getFields()) {
System.out.println(field.getName() + " - " + fieldMatches(field));
}
}
private static String fieldMatches(Field mapField) throws Exception {
if (!Map.class.isAssignableFrom(mapField.getType())) {
return "Field is not a Map";
}
if (!(mapField.getGenericType() instanceof ParameterizedType)) {
// We know it's a map, but it doesn't have type params. Probably something
// like this: class MyStringMap implements Map<String, String>. You can do
// something with getGenericInterfaces() but this seems so unlikely that
// it could just be ignored.
return "TODO";
}
final ParameterizedType mapType = (ParameterizedType) mapField.getGenericType();
final Type keyType = mapType.getActualTypeArguments()[0];
final Type valueType = mapType.getActualTypeArguments()[1];
if (Foo.class != keyType) {
return "Map's key type is not Foo";
}
if (!(valueType instanceof ParameterizedType)) {
// Same problem as above. May be a Set without type params
return "Map's value is (probably) not a Set";
}
final ParameterizedType pValueType = (ParameterizedType) valueType;
final Class<?> valueClass = pValueType.getRawType() instanceof Class ?
((Class<?>) pValueType.getRawType()) :
Application.class.getClassLoader().loadClass(
pValueType.getRawType().getTypeName()
);
if (!Set.class.isAssignableFrom(valueClass)) {
return "Map's value is not a Set";
}
final Type setElemType = pValueType.getActualTypeArguments()[0];
if (setElemType != Bar.class) {
return "Set's elements are not Bars";
}
return "Looks good";
}
}
Output:
good - Looks good
better - Looks good
notAMap - Field is not a Map
badKey - Map's key type is not Foo
badValue - Map's value is (probably) not a Set
badSetElems - Set's elements are not Bars
noTypeParamMap - TODO
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.