Get the type of generic T

JAX

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)).

OldCurmudgeon

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

How do I get a class instance of generic type T?

From Java

How to get the type of T from a member of a generic class or method?

From Dev

Get type of generic parameter

From Dev

Java get generic type of collection

From Dev

Can't serialize generic type

From Dev

Get list of entity objects by generic T which is type of EntityObject

From Dev

Get an instance of generic type

From Dev

Get ICollection property of generic type

From Dev

How to get the typeof(T) from a generic method with base type constraint?

From Dev

Generic repository with generic constructor of type T

From Dev

Get type of property in generic method

From Dev

Spring get generic type class

From Dev

Get array class of generic type

From Dev

Get generic type from a Function

From Dev

JavaPoet - get generic type

From Dev

What is the "type" of a generic IList<T>?

From Dev

Get generic parameters of a generic type

From Dev

Get Generic Type in ListView Item

From Dev

Get number of generic type parameters

From Dev

Generic props in react/typescript - how to get T to be the type of a property?

From Dev

How to get type of inherited generic

From Dev

Reading concrete class property within a generic method that doesn't get generic type instance

From Dev

Get type of Class from generic Class(of T)

From Dev

Get Type of ParameterizedType from generic

From Dev

Get generic parameters of a generic type

From Dev

Get Generic Type in ListView Item

From Dev

Reflection Get List<> from List<T> (Container type from generic container type)

From Dev

Get generic type of T in Kotlin

From Dev

How to get type of T generic?