Is there a way to get Class object from the type variable in Java generic class? Something like that:
public class Bar extends Foo<T> { public Class getParameterClass() { return T.class; // doesn't compile } }
This type information is available at compile time and therefore should not be affected by type erasure, so, theoretically, there should be a way to accomplish this. Does it exist?
A variable of an object type is also called a reference. The variable itself does not contain the object, but contains a reference to the object. The reference points to somewhere else in memory where the whole object is stored.
Creating an ObjectDeclaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
Java provides three different ways to find the type of an object at runtime like instanceof keyword, getClass(), and isInstance() method of java. lang. Class.
The Java Object getClass() method returns the class name of the object. The syntax of the getClass() method is: object.getClass()
This works:
public static class Bar extends Foo<String> { public Class<?> getParameterClass() { return (Class<?>) (((ParameterizedType)Bar.class.getGenericSuperclass()).getActualTypeArguments()[0]); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With