JPA标准路径的类型检查

时间:2019-02-04 15:58:02

标签: java jpa generics reflection typetoken

我有一个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),但是我发现以下工具可以检索通用类型参数:TypeTokenTypetoolsClassmate 。而且我不想让客户端通过Class<E>作为CollectionCriterion<E>的构造函数的参数。

感谢您的时间。

0 个答案:

没有答案