如何通过在Java中使用Reflection直接在bean类的私有Setter方法中设置值

时间:2019-01-05 07:25:30

标签: java spring reflection

我不能使用反射直接在User bean类的Setter方法中设置值

我只能访问那些getter方法,但不能在  用户Bean类的设置方法。

how to invoke setter method by reflection in java  Java中的反射方法

 //------->This My UserClass

public class User {

     private String name;
     private int age;

    private String getName() {
        return name;
    }
    private void setName(String name) {
        this.name = name;
    }
    private int getAge() {
        return age;
    }
    private void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + "]";
    }
 }
 //------> Then My Main Method 

 public static void main(String args[])
{
 try {
    User user = new User();
    Method method = User.class.getDeclaredMethod("setName", String.class);
    method.setAccessible(true);
    method.invoke(user, "Some name");
    System.out.println("user.getName() = " + user.getName());
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
    e.printStackTrace();
}
}

我想直接调用Setter方法并在Setter中设置可以反映在User Bean setter方法中的更改的值。请让我知道这是可能的。

2 个答案:

答案 0 :(得分:0)

这是因为您的setName()方法设置为私有。除了该类本身之外,您不能访问该类的任何私有方法。

将其更改为..

Plane

那么你会很好的。

答案 1 :(得分:0)

我执行了您的代码并正常工作。使用Reflection api,您可以将setAccessible设置为true来调用私有方法。