jeudi 30 juin 2022

Call JsonProperty setter method from a dependent class

I have a class as follows:

public class MyClass {
   @JsonProperty("my_id")
   private String id;

   @JsonProperty("my_list")
    private List<SecondClass> myList;

   public getId() {
      return this.id;
   }

   public setId(String id) {
      this.id = id;
   }

   public getMyList() {
      return this.myList;
   }

   public setMyList(List<SecondClass> myList) {
      this.myList = myList;
   }
}

My class has a dependency on another class called SecondClass [through the List entity]

public class SecondClass {
   @JsonProperty("my_name")
   private String name;

   public getName() {
      return this.name;
   }

   public setName(String name) {
      this.name = name;
   }
}

I know how to access the getters and setters of "MyClass" using Reflection based on the JsonProperty name, as shown below:

public void myMethod(MyClass myClass, String jsonProperty, String newId) throws IllegalAccessException {
    for (Field field : MyClass.class.getDeclaredFields()) {
        JsonProperty jsonPropAnnotation = field.getAnnotation(JsonProperty.class);
        if (jsonPropAnnotation != null)
            if (jsonPropAnnotation.value().equals(jsonProperty)) {
                field.setAccessible(true);
                field.set(myClass, newId);
            }
    }
}

But, my question is, is there a way to fetch the getter and setter from SecondClass via MyClass based on the JsonProperty name using Reflection?

As an example I would like to call getList() based on JsonProperty value "my_list" and then setName() based on the JsonProperty value "my_name".

Is this a possibility using reflection?





Aucun commentaire:

Enregistrer un commentaire