Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get "real" class of generic type

Tags:

java

generics

How can I get the "real" class of a generic type?

For Example:

public class MyClass<T> {
    public void method(){
        //something

        System.out.println(T.class) //causes a compile error, I wont the class name

        //something
    }
}

If T = Integer

Output:

java.lang.Integer

If T = String

Output:

java.lang.String

Thanks

like image 631
Diego D Avatar asked Apr 26 '11 01:04

Diego D


People also ask

How do you find the type of generic class?

You can get around the superfluous reference by providing a generic static factory method. Something like public static <T> GenericClass<T> of(Class<T> type) {...} and then call it as such: GenericClass<String> var = GenericClass. of(String. class) .

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

The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.


2 Answers

If you have a instance variable of type T in your class, and it happens to be set, then you could print the class of that variable.

public class Test<T> {

    T var;

    public static void main(String[] args) {
        Test<Integer> a = new Test<Integer>();
        System.out.println(a.boo());
        a.setVar(new Integer(10));
        System.out.println(a.boo());
    }

    public String boo() {
        if (var == null) {
            return "Don't know yet";
        }
        return var.getClass().getSimpleName();
    }

    public void setVar(T var) {
        this.var = var;
    }

    public T getVar() {
        return var;
    }
}
like image 79
Kal Avatar answered Oct 06 '22 21:10

Kal


You can't. The information is stripped from the code at compile time, a process that is known as type erasure. For more, please look here: Type Erasure

edit: sorry my bad, the information is not loaded at run time.

like image 27
Hovercraft Full Of Eels Avatar answered Oct 06 '22 21:10

Hovercraft Full Of Eels