• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to use instanceof in generics  RSS feed

 
tom chansky
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i realize there're some limitations in generics (J2SE 1.5); one of them is "naked" type parameter can't be used in instanceof operations.

for example:

class AClass<T> {

public void aMethod(Object arg) {
if(arg instanceof T) {} // Error

}
}

what if i need to check what class i'm dealing with? any ideas?
 
Mogens Nidding
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As far as I know, there is no way to do what you want directly - no type parameters are present at runtime.

If you need to check, your best bet is to take a class literal as argument, for example to the constructor. As a trick, use T as type parameter for the class, like this:



Hope this helps!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!