문제

I have a 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();           
    }
}

This class is get instantiated as:

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

    public MultiSortPageableController() {
        super();

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

The actual value of U is passed from the child class of MultiSortPageableController which is:

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

}

The ArticleSortField is an Enum.

I was expecting the method getCriteriaClass of MultipleSorting would return ArticleSortField from a method of MultiSortPageableController. But it is returning java.lang.Enum.

I am unable to figure it out why it is not returning the actual enum and how can I make it so. Any pointer would be very helpful to me. I need to get ArticleSortField.

Purpose:

I two requirement:

  1. To get the actual class of enum type (say ArticleSortField.class)
  2. To list enum value. If I have the enum class, then I could invoke class..getEnumConstants().
도움이 되었습니까?

해결책

Java compiler removes information about generics, therefore when you use reflection you get no information about the declared type, other than Enum. This process is called type erasure.

How about passing the type down, via the constructor, like this:

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);
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top