lundi 7 janvier 2019

how to invoke setter method by reflection API in java

How to invoke Bean private setter method by reflection in java. Suppose I have a User class with two Filed name & age this filed have setter and getter method Then I can try to set the value directly in Setter Method, not in filed Method.

   //This my User Bean Class

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;
   }

  //---> CallMethod Optional
  void callMethod() { System.out.println("Name :- "+name+" Age :-"+age); }

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

}
  //This my Main Method


public class TestClass {

    public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {

        User user = new User();
        Method method1 = User.class.getDeclaredMethod("setName",String.class);
        Method method2 = User.class.getDeclaredMethod("setAge",int.class);
        method1.setAccessible(true);
        method2.setAccessible(true);
        method1.invoke(user,"sanket");
        method2.invoke(user,21);

        user.callMethod();
    }
}

I would fallow that link content

This is my problem

Method method1 = User.class.getDeclaredMethod("setName",String.class);
Method method2 = User.class.getDeclaredMethod("setAge",int.class);

I am trying to do not hard code that I want directly dynamic type check and invoke the setter then set the value in the setter





Aucun commentaire:

Enregistrer un commentaire