4

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?

6
  • 2
    Why do you need this... ? Commented Apr 23, 2013 at 4:36
  • You have to create instance of nameOfClass by reflection Class.forName() and then create a list for that class. Commented Apr 23, 2013 at 4:36
  • 1
    @prasanth at runtime it is a List of Objects. Commented Apr 23, 2013 at 4:37
  • @LCYSoft - i think you need to use class name at runtime and want to product object. am i right? Commented Apr 23, 2013 at 4:59
  • Why not just have a variable called name in the class and set it? Commented Apr 23, 2013 at 5:05

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If you give a bit more context for why you need this, we may come up with an alternative to that end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.