I’ve a method in which I’m passing a generic argument. To execute one required method I need the class instance of the same. How can I get it.
There is a workaround which I’m using but I want to know how can we get the Class instance.
The snippet I’m using is:
public <T> T readModelWithId(Class<T> c, Serializable pk) {
// Some code here.
T t = (T)session.get(c, pk);
// Some code here.
return t;
}
The problem is that I don’t want to pass the Class instance in this method as it is same as the return type T which is of generic type.
You can’t do it because Java implements Generics using “type erasure”.
http://docs.oracle.com/javase/tutorial/java/generics/erasure.html
Looks like you are doing a generic DAO. I’ve done something similar here:
http://www.matthews-grout.co.uk/2012/01/my-generic-hibernate-dao.html