获取参数化类T的实际枚举类扩展Enum <! - ? - >

时间:2013-07-20 15:32:25

标签: java generics reflection enums parameterized-class

我有一个班级:

public class MultipleSorting<T extends Enum<?>> {
    private T criteriaType;

    public Class<T> getCriteriaClass() {
        Field field = ReflectionUtils.getField(getClass(),"criteriaType");
        ReflectionUtils.makeAccessible(field);
        return (Class<T>)field.getType();           
    }
}

此类被实例化为:

public abstract class MultiSortPageableController<T extends MultiSortPageableController<?,?>, U extends Enum<?>> {
    private MultipleSorting<U> multipleSorting;

    public MultiSortPageableController() {
        super();

        multipleSorting = new MultipleSorting<U>();
    }
}

U的实际值是从MultiSortPageableController的子类传递的:

public abstract class AbstractArticleSearchController<T extends AbstractArticleSearchController<T>> extends MultiSortPageableController<T,ArticleSortField> {

}

ArticleSortFieldEnum

我希望getCriteriaClass的{​​{1}}方法会从MultipleSorting的方法返回ArticleSortField。但它正在返回MultiSortPageableController

我无法弄清楚为什么它没有返回实际的枚举,我怎么能这样做。任何指针都对我很有帮助。我需要java.lang.Enum

目的:

我有两个要求:

  1. 获取枚举类型的实际类(例如ArticleSortField
  2. 列出枚举值。如果我有枚举类,那么我可以调用ArticleSortField.class

1 个答案:

答案 0 :(得分:1)

Java编译器删除有关泛型的信息,因此当您使用反射时,除了Enum之外,您不会获得有关声明类型的信息。此过程称为type erasure

如何通过构造函数向下传递类型,如下所示:

public class MultipleSorting<T extends Enum<?>> {
    private Class<T> criteriaType;

    MultipleSorting(Class<T> criteriaType) {
        this.criteriaType = criteriaType;
    }

    public Class<T> getCriteriaClass() {
        return criteriaType;
    }
}

public abstract class MultiSortPageableController<T extends MultiSortPageableController<?, ?>, U extends Enum<?>> {
    private MultipleSorting<U> multipleSorting;

    public MultiSortPageableController(Class<U> criteriaType) {
        super();

        multipleSorting = new MultipleSorting<U>(criteriaType);
    }
}

public abstract class AbstractArticleSearchController<T extends AbstractArticleSearchController<T>> extends MultiSortPageableController<T, ArticleSortField> {
    public AbstractArticleSearchController() {
        super(ArticleSortField.class);
    }
}