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