Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How do I create a list of a class from String

I want to create a list typed to the name of a class from a string. For example,

String nameOfClass = "com.my.list.class";
List list = new ArrayList<nameOfclass>();

I only know the type of class to be inserted into List in runtime in text format.

Is this possible?

like image 241
codereviewanskquestions Avatar asked Jan 14 '23 14:01

codereviewanskquestions


1 Answers

No.

Generic type annotations only happen at compile-time, they are erased from the runtime. When the program executes, the ArrayList does not know about its generic type.

So as a result, the type annotation is only useful for the compiler. If you don't know the type at compile time (program design time), then you cannot use them.

like image 146
Thilo Avatar answered Jan 21 '23 04:01

Thilo