• Post Reply Bookmark Topic Watch Topic
  • New Topic

Converting type parameters to class  RSS feed

 
Henrique Ordine
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd like to use a type parameter passed to my class as a Class.
I tried T.class but I get the error Cannot select from a type variable.

Here's my class:

public MyClass<T> {

public void myMethod() {
Class<T> clazz = T.class; // Cannot select from a type variable
}

}

Could anyone please help?
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you want is not possible, because of type erasure. That's also why "new T()" is not allowed - the actual class may not have a default constructor.

The only way to do this is pass a Class<T> object to either the constructor (in which case you need to store it in an instance variable) or to the method:

I suggest modifying the constructor because then you only need to pass the Class<T> object in one place - the same place where you're already typing in Integer anyway:

Just one question before you go through all this: what do you need the Class<T> for?
[ October 15, 2008: Message edited by: Rob Prime ]
 
Henrique Ordine
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply, rob.
I`d like to pass that Class<T> to methods such as EntityManager.find();
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then letting the calling code specify the Class object seems to be the only option, unless you want to do some casting. Which will still need the Class object to get a T out of the Object.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!