JAX
JAX

Reputation: 1620

Get the type of generic T

C# allows for getting the type of generic parameters using the typeof(T)method without the need to instantiating the T parameter. But in Java anytime I have generic T parameter and I want to determine the type I have to create an instance of that parameter,for example by using the Class<T> Type, to figure out what type that is.

In comparison with what C# provides, this approach in Java looks unnecessarily lengthy and complicated. I would like to know what is best alternative to determine the type of a generic parameter without the need to instantiate that (for example if (T is Integer)).

Upvotes: 1

Views: 2082

Answers (2)

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

Generics in Java is a compile-time feature - thus the mismatch between Java and C#. As a result you cannot do anything at run time to determine the type unless you are either passed an object of the type or create one yourself or actually told the class in some other way.

It is generally considered a bad idea to even try to find the type. It generally indicates that you have not designed your class hierarchy properly.

Upvotes: 4

AnthonyJClink
AnthonyJClink

Reputation: 1008

Generics are compile-time true... but you can give the compiler hints of what t really is.

by passing in the actual runtime class of what T really is, you allow the compiler to allow you runtime knowlege of the class T represents.

example:

public <T> boolean isObjectT(Class<T> type, Object object){
    return object.getClass().isAssignableFrom(type);
}

The answer on this question kinda spells out the limits of parameterized types:

Java: How do I specify a class of a class method argument?

If you are simply trying to get information from subclasses... you could try the reflection with paramterized types on this question:

How to determine the class of a generic type?

I have had good luck with that for more complex requirements.

Upvotes: 0

Related Questions