How can I call getter/setter for property marked w

2019-09-18 03:38发布

问题:

I am currently creating a custom marshalling tool for parsing an excel file. I would like to know how I can first find all properties with a custom annotation (this needs to take inheritance into account, so more than getDeclaredFields), then based on what method I am using call the corresponding getter or setter. Right now, I am just focusing on the setter.

Current Code:

private <T> T findAnnotations(Class<T> clazz)
 {
    T obj  = null;

    Annotation[] annotations = clazz.getAnnotations();

    for(Annotation annotation : annotations)
    {
        if(annotation.annotationType() == ExcelColumn.class)
        {
            if(obj == null)
            {
                try {
                    obj = clazz.newInstance();
                } catch (IllegalAccessException | InstantiationException e) {
                }
            }
            //annotation found
            //call setter of property
            //using ChildTest sample class call setname and set parent name 
            //with string previously parsed.
            // i.e obj.setName("") and obj.setParentName("") 
        }
    }
    return obj;
}

Sample Class:

public class ChildTest extends Parent{
     @ExcelColumn
     private String name;
     public void setName(String name) {
          this.name = name;
     }
}

public class Parent{
     @ExcelColumn
     private String parentName;
     public void setParentName(String parentName) {
          this.parentName= parentName;
     }
 }

回答1:

You can use reflection to invoke those methods.

obj.getClass().getMethod("setName", String.class).invoke(obj, "Name");
obj.getClass().getMethod("setParentName", String.class).invoke(obj, "Parent name");