How to get a class for a generic type?

How to create Classthat represents a shared object?

List<String> list = new List<String>();
Class c1 = list.class;
Class c2 = Class.forName(???); // <- how?
assert c1 == c2;
+3
source share
3 answers

A class object does not depend on a specific class that satisfies its type parameter:

assert (new ArrayList<String>()).getClass() == (new ArrayList<Integer>()).getClass();

This is the same object, regardless of how it is typed.

+5
source

You cannot, because general information is missing at runtime, due to the type of erasure .

Your code can be written as follows:

List<String> list = new ArrayList<String>();
Class c1 = list.getClass();
Class c2 = Class.forName("java.util.ArrayList");
System.out.println(c1 == c2); // true
+6
source

Class . - java.lang.reflect.Type, ParameterizedType. .

(. generics - , . API .)

+2
source

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


All Articles