Reputation: 638
I was wondering if there's a way to, in Java, use a generic type within a generic method without requiring an argument specifying the class type. Here's the normal way of doing it:
public <T> T doSomethingGeneric(Class<T> type, int a) {
return (T) doSomethingElse(type, a);
}
I would like this as an alternative:
public <T> T doSomethingGeneric(int a) {
return (T) doSomethingElse(/* some magic with T here */, a);
}
Background: I'm writing utility methods with Hibernate. Here's an example of what I'm actually trying to do, and you can infer how it applies to this problem.
public static <M extends Model> M get(Class<M> type, Serializable id) {
Session session = newSession();
Transaction t = session.beginTransaction();
Object model = null;
try {
model = session.get(type, id);
t.commit();
} catch (HibernateException ex) {
t.rollback();
throw ex;
}
return (M) model;
}
Is this possible? If so, how is it done? Thanks!
Upvotes: 1
Views: 452
Reputation: 360066
You want to get a Class<T>
at runtime to pass to doSomethingElse()
? No, that is not possible.
If you describe why doSomethingElse
needs a Class<T>
, perhaps we could suggest a workaround.
Upvotes: 4
Reputation: 200306
This isn't possible: the code of doSomethingGeneric
is only compiled once, unlike the instantiation of a template in C++. The type T
is erased to Object
in the process.
Notice also that (T)
will be flagged as an unchecked downcast.
Upvotes: 2