如何从 genericReturnType 创建实例

How to create Instance from genericReturnType

这里我需要创建一个java.util.List的对象,其中 我有 java.util.List 仅作为字符串可用。

演示 class

class Demo {
    public List<User> allUser() {
        // some stuff
    }
}

另一个class

Method method = null;
try {
         Class cls= Class.forName("Demo"); // fully qualified Name here for sure
         
         Method[] methods = cls.getMethods();
         for (Method _method:methods) {
             if(_method.getName().equals("allUser")) {
                method = _method;
                break;
             }
         }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if(method != null) {
            java.lang.reflect.Type genericReturnType = method.getGenericReturnType();
    }

这里我需要创建一个java.util.List的对象,我只有 genericReturnType = java.util.List

我试过了

Class clazz = Class.forName(genericReturnType.getTypeName());

这个returns java.lang.ClassNotFoundException

我想创建 java.util.List

的实例

问题是方法 allUser 可以是任何东西,return 类型的方法可以是任何东西

东西直到方法 genericReturnType 看起来不错。我需要在 genericReturnType 的帮助下创建一个对象。

注意:考虑到代码中没有任何句法错误。

让我简化一下。

// I want to achive this
String clsName = "java.util.List<com.entity.User>";  // consider fully qualified name
Class cls = Class.forName(clsName); // from here I got error java.lang.ClassNotFoundException
Object clsInstance = (Object) cls.newInstance();

如果有用户列表,我想用 com.entity.User 做一些处理,(那里可能有任何类型的列表而不是用户)所以 我需要识别通用类型也是 List.

提前致谢。

您可以在将 Type 转换为 ParameterizedType 后提取通用类型:

ReflectionTest.java

public class ReflectionTest {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Method method = null;
        try {
            Class cls = Class.forName("Demo"); // fully qualified Name here for sure

            Method[] methods = cls.getMethods();
            for (Method _method : methods) {
                if (_method.getName().equals("allUser")) {
                    method = _method;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (method != null) {
            System.out.println(method.getReturnType());
            ParameterizedType parameterizedType = (ParameterizedType) method.getGenericReturnType();

            if (parameterizedType.getActualTypeArguments().length > 0 && parameterizedType.getActualTypeArguments()[0] instanceof Class<?>) {
                Class type = (Class) parameterizedType.getActualTypeArguments()[0];

                User user = (User) type.newInstance();

                System.out.println(user.getClass());
            }
        }
    }
}

class Demo {
    public List<User> allUser() {
        return Collections.emptyList();
    }
}

User.java

public class User {

}