T.class
Hey there. I'm stuck with this one:
I want to do something like this:
publicclass Something<T>{
publicvoid f(){
Class clazz = T.class;//error: cannot select from a type variable
if(T.equals()){
System.out.println("Hurray!");
}
}
}
but I get an error (cannot select from a type variable) in line 3. Any ideas?
Thanks in advance!
S.
A common Idiom with generics is that when you need the Class of a type variable, you pass it in the constructor. The compiler will make sure you only get passed a valid Class<T>.
You can't get the compiler / language to tell you what T.class is, but you can force the user of your class to tell you, and the compiler can make sure they don't tell lies.
For example
public class Something<T>{
public Something(Class<T> clazz) {
this.clazz = clazz;
}
public void f(){
// you can use clazz here, it contains T.class, but your code was odd here
}
}
If you try to compilenew Something<String>(String.class);
it will succeed, but new Something<String>(Integer.class);
will fail.
Bruce