我想测试MyType<int>
类型的字段是否为MyType<?>
子类型的字段。
如果该字段的类型为MyType<?>
,那么我会使用getActualTypeArguments
的{{1}}正确实例化。
但我无法进行测试:
ParameterizedType
......不会编译并得到我:
if( (field.getType instanceof MyType<?>) )
Incompatible conditional operand types Class<capture#3-of ?> and myType<?>
是我创建的通用类。
该字段是使用反射从类中获取的字段(myType
的实例,它公开了getType方法)。
任何人都知道如何?
答案 0 :(得分:0)
Field#getType()
方法返回一个Class<?>
对象,表示该字段类型的Class
实例。在这种情况下,您将获得Class<MyType>
。当然,这不能是MyType<?>
的实例。这是Class
的实例。
如果您想查看该字段是MyType<?>
类型还是其子类型,那么您需要从该Class
对象获取实例:
if (field.getType().newInstance() instanceof MyType<?>) {
System.out.println("Field is of type MyType<?>");
}
您也可以使用Class#isAssignableFrom()
方法执行此操作:
if (MyType.class.isAssignableFrom(field.getType()) {
System.out.println("Field is of type MyType<?>");
}