How To Instantiate a java.util.ArrayList with Generic Class Using Reflection? I am writing a method that sets java.util.List on target object. A target object and a generic type of list is knowing in runtime:
public static void initializeList(Object targetObject, PropertyDescriptor prop, String gtype) {
try {
Class clazz = Class.forName("java.util.ArrayList<"+gtype+">");
Object newInstance = clazz.newInstance();
prop.getWriteMethod().invoke(targetObject, newInstance);
} catch (Exception e) {
e.printStackTrace();
}
}
Generic types are instantiated to form parameterized types by providing actual type arguments that replace the formal type parameters. A class like LinkedList<E> is a generic type, that has a type parameter E .
We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.
Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.
An object doesn't know about its generic type at execution time. Just create a new instance of the raw type (java.util.ArrayList
). The target object won't know the difference (because there isn't any difference).
Basically Java generics is a compile-time trick, with metadata in the compiled classes but just casting at execution time. See the Java generics FAQ for more information.
There's no need to do any reflection for creating your List. Just pass in some additional type information (usually done by passing a class of the correct type).
public static <T> List<T> createListOfType(Class<T> type) {
return new ArrayList<T>();
}
Now you have a list of the required type you can presumably/hopefully set it directly on your targetObject
without any reflection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With