首页 > 解决方案 > 解析 Java 反射类

问题描述

假设我有一个名为的方法Object classInstance = createInstance("Page", map, factory),它使用 java 反射创建一个“Page”实例并用它做一些事情。出于演示目的,我将其称为“页面”,但它可以是我的任何类。

现在我想将此对象添加到List<Page>. 要调用list.add(classInstance)并将其添加到列表中,我需要将其解析为“页面”。鉴于我拥有的唯一信息是包含类名的字符串,有没有办法做到这一点?因此,(Page) classInstance我不需要做类似的事情(Class.forName("Page")) classInstance

我无法修改列表或将其添加到列表的方式。

谢谢你。

编辑:这里是 createInstance 方法:

    private static Object createInstance(String className, Map<?, ?> map, Meilenstein2Factory factory) throws InvocationTargetException, IllegalAccessException {

    try {
        String createMethodName = "create" + className;
        Method createMethod = factory.getClass().getMethod(createMethodName);
        Object classInstance = createMethod.invoke(factory);
        
        
        String methodName = "";
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            try {
                methodName = "set" + entry.getKey().toString().substring(0,1).toUpperCase() + entry.getKey().toString().substring(1);
                Method setNameMethod = classInstance.getClass().getMethod(methodName, getType(entry.getValue()));
                setNameMethod.invoke(classInstance, parseEntry(entry.getValue()));
            } catch (NoSuchMethodException e) {
                LOGGER.log(null, "Attribute " + entry.getKey().toString() + " is not a valid attribute for this object. Is it spelled correctly?");
            }
            
        }
        return classInstance;
    } catch(NoSuchMethodException nm) {
        LOGGER.log(null, "Folder " + className + " does not reference to a valid object. Is it spelled correctly?");
    }
    return null;

}

编辑 2:错误和调试器的屏幕截图

不用关心Page和PageImpl,我在问题中使用Page来简化,但是工厂接受Interface Page并返回PageImpl的实例。正如您在第二个屏幕截图中看到的那样,该对象是 PageImpl 的一个实例,所以这似乎是正确的。

在此处输入图像描述

在此处输入图像描述

编辑3: 在此处输入图像描述

编辑 4:现在有效的东西:

String methodName = "get" + "Page";
        Method getListMethod = site.getClass().getMethod(methodName);
        List<Object> list = (List<Object>) getListMethod.invoke(site);
        list.add(page);

标签: javareflection

解决方案


您的方法createInstance返回一个Class<Page>(类对象),但您的列表是一个List<Page>(实例列表)。

您将需要创建一个实例并将其添加到列表中,仍然使用反射:

list.add(classInstance.getDeclaredConstructor().newInstance());

以上是为类使用一个空的构造函数Page。例如,如果您想使用一个带有一个字符串和一个 int 的构造函数,您可以这样做:

list.add(classInstance.getDeclaredConstructor(String.class, Integer.class).newInstance("my string", 4));

编辑:。由于classInstance是一个对象而不是一个类,你应该能够做到这一点:

list.add(Class.forName("Page").cast(classInstance));

推荐阅读