Reputation: 5040
How can I invoke a particular method on a generic type? I want to invoke a a getter/setter method.
Edit: Ex:
class BurningSun<T>
{
public void kitchenSink()
{
Class c = Class.forName(/*What to put here for <T> ?*/)
/*
Reflections code
*/
}
}
Hmmm, so how are the bean's getter methods invoked and set in various frameworks?
Upvotes: 0
Views: 944
Reputation: 74750
Inside of a generic type there is no way to get the name of the type parameter at runtime if nobody did tell it to you.
On runtime, a BurningSun<String>
and BurningSun<Integer>
are completely equivalent, and you can even cast one into the other (this is not type safe, though).
So, usually if you really need the class object of the type parameter inside your generic object, you let someone give it to you in the constructor.
class BurningSun<T> {
private Class<T> paramClass;
public BurningSun(Class<T> pClass) {
this.paramClass = pClass;
}
public void kitchenSink() {
T t = paramClass.newInstance();
}
}
(You would need to catch or declare some exceptions here.)
Upvotes: 3
Reputation: 11976
Well all method invocation based on reflection is at its most simple about shoving Objects into the method, praying it'll work. So cast & keep your fingers crossed.
Upvotes: 2