A class which has a method declared as this:
public class A{
public <T> T test(java.lang.Class<T> classOfT)
}
Normally it can be called against an object like this:
A a = new A()
String s = "test";
a.test(String.class); //I wrote this as s.class at first,which is wrong.Thanks Nick.
Now I would like to generalize the object passed to it, so I declare a class like this:
public class B <T>{
private A a = new A();
private T obj = null;
T test(){return a.test(obj.getClass()); }
}
But the code wont’ compile.I am wondering is it possible to achieve my goal?
Thank you in advance Java gurus 😉
The last line returns
Class<? extends T>— butTis unbounded, so it is basically bounded byObject, which means it returnsClass<? extends Object>, which is the same asClass<?>.So doing this:
Will actually invoke
a.testwith a parameter of typeClass<?>, which returns anObject, and not aT.Just cast the parameter to
Class<T>or the return type toTand it should work — although I am yet to understand why you need something like this. Also, there is this strange error in the original post:Doing
"test".classis wrong — it should beString.class.