Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How To: Use reflection to create instance of generic type?

843793Feb 1 2006 — edited Mar 22 2006
I would like to be able to use reflection to instantiate an instance of a generic type, but can't seem to avoid getting type safety warnings from the compiler. (I'm using Eclipse 3.1.1) Here is a trivial example: suppose I want to create an instance of a list of strings using reflection.

My first guess was to write the following:
Class cls = Class.forName("java.util.ArrayList<String>");
List<String> myList = cls.newInstance();
The call to Class.forName throws a ClassNotFoundException. OK, fine, so I tried this:
Class cls = Class.forName("java.util.ArrayList");
List<String> myList = cls.newInstance();
Now the second line generates the warning "Type safety: The expression of type List needs unchecked conversion to conform to List<String>".

If I change the second line to
List<String> myList = (List<String>)cls.newInstance();
then I get the compiler warning "Type safety: The cast from Object to List<String> is actually checking against the erased type List".

This is a trivial example that illustrates my problem. What I am trying to do is to persist type-safe lists to an XML file, and then read them back in from XML into type-safe lists. When reading them back in, I don't know the type of the elements in the list until run time, so I need to use reflection to create an instance of a type-safe list.

Is this erasure business prohibiting me from doing this? Or does the reflection API provide a way for me to specify at run time the type of the elements in the list? If so, I don't see it. Is my only recourse to simply ignore the type safety warnings?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 19 2006
Added on Feb 1 2006
52 comments
4,014 views