如何使用反射 api 访问 bean class 的 getter 方法?

How to access getter method of bean class using reflection api?

如果我使用反射 API 实例化 class,为什么 variable2 的值为空?

其中,Variable1 的值按​​照集合正确返回,这里我正常实例化了对象。 如何使用 ReflectionAPI 获取 variable2 的值?

    package com.OP.app;

    public class Bean {

    private String variable1;
    private String variable2;
    public String getVariable1() {
        return variable1;
    }
    public void setVariable1(String variable1) {
        this.variable1 = variable1;
    }
    public String getVariable2() {
        return variable2;
    }
    public void setVariable2(String variable2) {
        this.variable2 = variable2;
    }


}

package com.OP.app;

import java.lang.reflect.Method;

public class ObjectCall {

    public static void main(String []args){
        Bean beanobject = new Bean();
        beanobject.setVariable1("Ram");
        beanobject.setVariable2("Rakesh");
        System.out.println(beanobject.getVariable1());
        String path = "com.OP.app.Bean";
        Class<?> newClass;
        try {
            newClass = Class.forName(path);
            Object obj = newClass.newInstance();
             String getMethod = "getVariable2";
             Method getNameMethod = obj.getClass().getMethod(getMethod);
             String name = (String) getNameMethod.invoke(obj); 
             System.out.println(name);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } // convert string classname to class
      }
    }

输出: 内存 空

那是因为您在新创建的对象(例如 obj)上调用方法,该对象没有为 variable1variable2 设置值,例如:

Object obj = newClass.newInstance();

以上将创建一个新的 Object of Bean class,variable1variable2 的值为 null。如果要打印在 beanobject 方法中设置的值,则需要使用 beanobject 调用 getter 方法。即改变

String name = (String) getNameMethod.invoke(obj); 

String name = (String) getNameMethod.invoke(beanobject);

您创建了目标 class 的新实例,其中没有设置任何值。

Object obj = newClass.newInstance();         
Method getNameMethod = obj.getClass().getMethod(getMethod);

更改此行,它应该可以工作:

Method getNameMethod = beanobject.getClass().getMethod(getMethod);

补充: 您对变量的命名不是很好。我会将代码重构为这样以便更好地阅读:

public static void main(String[] args) {
    Bean beanInstance = new Bean();
    beanInstance.setVariable1("Ram");
    beanInstance.setVariable2("Rakesh");

    System.out.println("Value 1 of fresh bean instance: " + beanInstance.getVariable1());

    String beanType = Bean.class.getName();
    Class<?> beanClazz;

    try {
        beanClazz = Class.forName(beanType);

        String getterMethodName = "getVariable2";
        Method getterMethod = beanClazz.getMethod(getterMethodName);
        Object returnValue = getterMethod.invoke(beanInstance);

        System.out.println("Value 2 of by reflection loaded bean instance: " + String.valueOf(returnValue));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } // convert string classname to class
}