我有一个CollectionCriterion类,定义如下:
public class CollectionCriterion<E>
...
//this is a standard JPA path expression to a field (for instance field1.field2.field3
private String pathExpression;
//this is the entity class
private Class<?> entityClass
...
public void validateField() throws IllegalStateException {
...
//here I retrieve the field corresponding to the path expression
//for instance I retrieve the field country corresponding to the
//path "person.address.country"
Field field = JpaUtils.navigateTo(entityClass, pathExpression);
//here I have to check that the retrieved field is a Collection
//of elements of type E (Collection<E>)
if(!Collection.class.isAssignableFrom(field.getType())) {
throw new IllegalArgumentException(...);
}
else {
//if it's a collection check if it contains only
//instances of E
}
...
}
}
给出以下实体类:
@Entity
public class A {
...
private Collection<String> collection;
...
}
我可以使用Java反射从字段java.lang.String
中检索collection
类型的参数:
Field field = A.class.getDeclaredField("collection");
ParameterizedType fieldType = (ParameterizedType) field.getGenericType();
Class<?> fieldTypeParameter = (Class<?>) fieldType.getActualTypeArguments()[0]; //here i get java.lang.String class.
如何从E
中检索类型参数CollectionCriterion<E>
并将其与字段的类型参数进行比较?
我知道运行时的类型擦除(here from stackoverflow),但是我发现以下工具可以检索通用类型参数:TypeToken,Typetools和Classmate 。而且我不想让客户端通过Class<E>
作为CollectionCriterion<E>
的构造函数的参数。
感谢您的时间。