Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the type of a parametrized class parameter?

I have the following class

public class MyClass<T> {
    public Class<T> getDomainClass() {
          GET THE CLASS OF T
    }
}

I've googled this problem and all the answers I could find told me to use getGenericSuperClass(), but the problem of this method is that I must have a second class that extends MyClass and I don't want to do this. What I need is to get the parametrized type of a concrete class?

like image 457
GuidoMB Avatar asked Jun 13 '10 18:06

GuidoMB


People also ask

What is class type parameter?

The type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.

What is a class 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 type parameters in generics?

In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type.

How do you declare a type parameter?

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number . Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).


1 Answers

You can't. The information you want (i.e. the value of T) is not available at run-time due to type-erasure.

like image 115
sepp2k Avatar answered Sep 22 '22 01:09

sepp2k