Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Class for generic type?

Tags:

java

How can I create a Class that represents a generic object?

List<String> list = new List<String>();
Class c1 = list.class;
Class c2 = Class.forName(???); // <- how?
assert c1 == c2;
like image 679
yegor256 Avatar asked Feb 17 '11 14:02

yegor256


People also ask

What is generic type class?

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.

Can classes be generic?

A generic class can be a base class to other generic or non-generic classes or abstract classes. A generic class can be derived from other generic or non-generic interfaces, classes, or abstract classes.

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

A Generic Version of the Box Class The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called type variables) T1, T2, ..., and Tn.


1 Answers

A class object is not specific to the particular class that is satisfying its type parameter:

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

It's the exact same object regardless of how it's typed.

like image 113
Mark Peters Avatar answered Oct 21 '22 03:10

Mark Peters