I read the article at
https://www.hibernate.org/328.html and tried to test to see if my concept is correct or not. As I understand, the statement
Code:
this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
is trying to obtain superclass's parameterized type e.g. T
But when trying to practise to see if my concept is correct or not, I found out the code I use is alway wrong by throwing
Code:
Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
at Child.<init>(Child.java:8)
at Test$1.<init>(Test.java:6)
at Test.process(Test.java:6)
at Test.main(Test.java:3)
The code I use is as below:
Code:
import java.io.Serializable;
public interface Father<T, ID extends Serializable>{
}
Code:
import java.io.Serializable;
import java.lang.reflect.*;
public abstract class Child<T, ID extends Serializable> implements Father<T, ID>{
private Class<T> persistentClass;
public Child(){
this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
/*
Type t = getClass().getGenericSuperclass();
Type arg;
if(t instanceof ParameterizedType){
arg = ((ParameterizedType)t).getActualTypeArguments()[0];
}else if(t instanceof Class){
arg = ((ParameterizedType)((Class)t).getGenericSuperclass()).getActualTypeArguments()[0];
}else{
throw new RuntimeException("Can not handle type construction for '"+getClass()+"'!");
}
if(arg instanceof Class){
this.persistentClass = (Class<T>)arg;
}else if(arg instanceof ParameterizedType){
this.persistentClass = (Class<T>)((ParameterizedType)arg).getRawType();
}else{
throw new RuntimeException("Problem dtermining generic class for '"+getClass()+"'! ");
}
*/
}
public Class<T> getPersistentClass(){
return this.persistentClass;
}
}
Code:
public class Test{
public static void main(String args[]){
new Test().process();
}
void process(){
Child c = new Child(){};
System.out.println(c.getPersistentClass());
}
}
Why can't the line getClass().getGenericSuperclass()... be converted to ParameterizedType? I am confused.
I appreciate any help.
Thank you very much