我有一个这样的简单的界面。Java获取通用类型不扩展
public interface EntityClass
{
public void setId(final Integer id);
public Integer getId();
}
和一类
public Student implements EntityClass{}
但这段代码是给我的错误,我想知道Generic Type
public class MyGenericType<T extends EntityClass>
{
private final Class<? extends EntityClass>genericClazz;
public MyGenericType()
{
genericClazz=(Class<? extends EntityClass>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
return;
}
}
后来我尝试这这样的代码
public static void main(String[] args)
{
final MyGenericType<Student>action = new MyGenericType<>();
}
但它抛出
Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
此代码我一直在使用它,但从子类扩展,但我不想从我的GenericType
延伸任何类。
我能做些什么才能从此代码中获得Student
类型。
final MyGenericType<Student>action = new MyGenericType<>();
,因为我需要得到一个Hibernate namedQuery.
只有这样,才能捕捉在泛型类型信息运行时通过'extends'语句。任何其他类型的信息都将被删除。 – Jonathan 2015-03-13 19:33:51