How can I call getter/setter for property marked with custom annotation?

时间秒杀一切 提交于 2019-12-12 06:20:01

问题


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");


来源:https://stackoverflow.com/questions/29565482/how-can-i-call-getter-setter-for-property-marked-with-custom-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!