This discussion is archived
4 Replies Latest reply: Apr 14, 2011 6:11 AM by 803691 RSS

How To Instantiate a Generic Class Using Reflection

824121 Newbie
Currently Being Moderated
How To Instantiate a java.util.ArrayList with Generic Class Using Reflection? I am writing a method that sets java.util.List<T> on target object. Target object and generic type of list is knowing in runtime:

<code>public static void initializeList(Object targetObject, PropertyDescriptor prop, String genericType) {
try {
Class clazz = Class.forName("java.util.ArrayList<"" *++genericType++* ">");
Object newInstance = clazz.newInstance();
prop.getWriteMethod().invoke(targetObject, newInstance);
} catch (Exception e) {
e.printStackTrace();
}
}<code>

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points