samedi 5 janvier 2019

How to set the values directly in private Setter method in bean class by using Reflection in java

I can't set the the values directly in Setter Method of my User bean class using reflection

I can only access those getter method but i can't set the value in the Setter method of User Bean Class.

how to invoke setter method by reflection in java method-by-reflection-in-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();
}
}

I want call the Setter method directly in and set the value in Setter that changes can reflected in User Bean setter method. Please let me Know is that possible.





Aucun commentaire:

Enregistrer un commentaire