Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Instantiate a java.util.ArrayList with Generic Class Using Reflection

Tags:

java

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();
    }
}
like image 989
user592433 Avatar asked Jan 27 '11 15:01

user592433


People also ask

Can you instantiate a generic class?

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 .

How do you create a object of a class using reflection?

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.

What is reflection class in Java?

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.


2 Answers

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.

like image 92
Jon Skeet Avatar answered Oct 06 '22 01:10

Jon Skeet


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.

like image 34
alpian Avatar answered Oct 06 '22 01:10

alpian