How to use reflection to instantiate Java. Net using generics util. ArrayList

How to use reflection to instantiate Java. Net using generic classes util. ArrayList? I'm writing a program that sets Java. Net on the target object util. List method The runtime knows the list of target objects and common types:

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();
    }
}

Solution

Object does not know its generic type at execution time Just create a new instance type (Java. Util. ArrayList) The target object will not know the difference (because there is no difference)

Basically, Java generics is a compile time technique. Metadata is used in compiled classes, and only conversion is performed at execution time For more information, see the Java genetics FAQ

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>