[英]Get actual enum class of the Parameterized class T extends Enum<?>
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: U
的实际值是从MultiSortPageableController
的子类传递的,该子类是:
public abstract class AbstractArticleSearchController<T extends AbstractArticleSearchController<T>> extends MultiSortPageableController<T,ArticleSortField> {
}
The ArticleSortField
is an Enum
. ArticleSortField
是一个Enum
。
I was expecting the method getCriteriaClass
of MultipleSorting
would return ArticleSortField
from a method of MultiSortPageableController
. 我期待方法
getCriteriaClass
的MultipleSorting
将返回ArticleSortField
从方法MultiSortPageableController
。 But it is returning java.lang.Enum
. 但是它返回
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
. 我需要获取
ArticleSortField
。
I two requirement: 我有两个要求:
ArticleSortField.class
) ArticleSortField.class
) class..getEnumConstants()
. class..getEnumConstants()
。 Java compiler removes information about generics, therefore when you use reflection you get no information about the declared type, other than Enum. Java编译器会删除有关泛型的信息,因此,当您使用反射时,除了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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.