Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: instanceof Generic

Isn't there any way to find the class-type of a generic?

if (T instanceof String) {     // do something... } 

The above definitely does not compile.

like image 556
someguy Avatar asked Jan 16 '11 10:01

someguy


People also ask

Does Instanceof work with generics?

Using generics to define the type in instanceofThe type used with instanceof has to be reifiable, which means that all information about the type has to be available at runtime, and this is usually not the case for generic types. Since types are gone, it's not possible for the JVM to know which type is T .

What is a generic type parameter in Java?

A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.

What is Java generics with examples?

Generics add that type of safety feature. We will discuss that type of safety feature in later examples. Generics in Java are similar to templates in C++. For example, classes like HashSet, ArrayList, HashMap, etc., use generics very well.


1 Answers

Generics are a compile time feature. Generics add checks at compile time which may not have any meaning at runtime. This is one example. You can only check the type of the object referenced which could be a super type in code. If you want to pass the type T you have do this explicitly.

void someMethod(Class<T> tClass) {     if(String.class.isAssignableFrom(tClass))  

or

void someMethod(Class<T> tClass, T tArg) { 

Note: the type might not be the same,

someMethod(Number.class, 1); 
like image 96
Peter Lawrey Avatar answered Sep 19 '22 18:09

Peter Lawrey