简体   繁体   中英

Getting class instance from generic type in Java

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.

There's no way you can get to something like T.class within that method, so you must pass the class argument since you need it to get your model object from the session.

Moreover, this adds a bit of extra "type-safety". You will force the caller to specify the return type as an argument, so the returned type will not just be "anything a caller may expect" (although I agree this makes it redundant).

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

You cannot do anything with generics that you could not do with non-generics with casts. Consider the non-generic version of your code:

public Object readModelWithId(Class c, Serializable pk) {
    // Some code here.
    Object t = session.get(c, pk);
    // Some code here.
    return t;
}

Now ask the same question, can you get rid of the class instance argument c ?

Generics are more for compile time type safety - you need class instance so compiler does not complain about missing cast. Alternatively you can ditch generics altogether and cast result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM