codereviewanskquestions
codereviewanskquestions

Reputation: 14008

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?

Upvotes: 4

Views: 124

Answers (1)

Thilo
Thilo

Reputation: 262852

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.

Upvotes: 9

Related Questions