Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I learn actual type argument of an generic class? [duplicate]

I have a parameterized class :

class ParameterizedClass<T extends AbstractSomething> {
}

calling:

new ParameterizedClass<Something>();

So how can I get actual type Something of T by using Java Generics?

like image 576
TanerDiler Avatar asked Aug 19 '10 08:08

TanerDiler


People also ask

How do I know the type of generic class?

In order to check the generic type, we need to create an instance of the generic class<T> and then we can compare the same with our class.

Which types can be used as arguments of a generic type?

The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).

Can a generic class have multiple generic parameters?

A Generic class can have muliple type parameters.

Can we define more than one generic datatype in a class?

You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.


1 Answers

It can be done, but type erasure can make it very hard. As the other answers discuss, you either have to make a subclass of ParameterizedClass or add a field of type T to ParameterizedClass, and the reflection code you need to do it is convoluted.

What I recommend in these circumstances, is to work around the issue like this:

class ParameterizedClass<T> {
    private Class<T> type;

    /** Factory method */
    public static <T> ParameterizedClass<T> of(Class<T> type) {
        return new ParameterizedClass<T>(type);
    }

    /** Private constructor; use the factory method instead */
    private ParameterizedClass(Class<T> type) {
        this.type = type;
    }

    // Do something useful with type
}

Due to Java's type inference for static methods, you can construct your class without too much extra boilerplate:

ParameterizedClass<Something> foo = ParameterizedClass.of(Something.class);

That way, your ParameterizedClass is fully generic and type-safe, and you still have access to the class object.

EDIT: Addressed the comment

like image 113
jqno Avatar answered Sep 27 '22 22:09

jqno