pratikabu
pratikabu

Reputation: 1688

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.

Upvotes: 1

Views: 1525

Answers (4)

Dan
Dan

Reputation: 1018

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

Upvotes: 2

newacct
newacct

Reputation: 122518

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?

Upvotes: 0

Costi Ciudatu
Costi Ciudatu

Reputation: 38265

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).

Upvotes: 3

Konstantin Pribluda
Konstantin Pribluda

Reputation: 12367

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

Upvotes: -1

Related Questions