How to specify information about a class of a generic type at compile time?

I have a class defined as follows:

public class GenericClass<T> {

 private final Class<T> type;

 public GenericClass(Class<T> type) {
      this.type = type;
 }

 public Class<T> getMyType() {
     return this.type;
 }
}

With this class code, it is easy to instantiate a new class with a non-generic type. For instance:

GenericClass<String> c = new GenericClass<String>(String.class)

My question is the following. How to create a new instance of a class with a common type? Example:

GenericClass<List<String>> c = new GenericClass<List<String>>(...)

If I put List<String>.class, the compiler will give me an error. At compile time, what syntax should be used to indicate the constructor of the right class of the generic type?

+4
source share
4 answers

, , List<String>.class, List.class. ? List<?>.class ? List<? extends AnotherClass>.class? , , , , , , .

+1

generics (, , ) - GenericClass. :

GenericClass<List<String>> c = new GenericClass<List<String>>(...){};

( trailing {}).

0

:

public class GenericClass<T> {
    Class<T> type;

    @SuppressWarnings("unchecked")
    public GenericClass() {
        Type type = ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
        if (type instanceof Class<?>)
            this.type = (Class<T>)type;
        else if (type instanceof ParameterizedType)
            this.type = (Class<T>) ((ParameterizedType)type).getRawType();
        else
            this.type = null;
    }

    public Class<T> getType() {
        return type;
    }
}

:

public static void main(String[] args) {
    GenericClass<Integer> g = new GenericClass<Integer>() {};
    System.out.println(g.getType());

    GenericClass<List<String>> g2 = new GenericClass<List<String>>() {};
    System.out.println(g2.getType());
}
0

Your problem is that there is only one class object Listthat you can get from List.class. But it Class<List>, Class<List<Object>>, Class<List<String>>or Class<List<?>>etc? It can have only one type, and Java developers have chosen Class<List>(this is the only safe choice). If you really want to Class<List<String>>, you will need to make some unverified throws:

GenericClass<List<String>> c =
    new GenericClass<List<String>>((Class<List<String>>)(Class<?>)List.class);
0
source

Source: https://habr.com/ru/post/1546159/


All Articles