如何为标有自定义注释的属性调用 getter/setter? [英] How can I call getter/setter for property marked with custom annotation?

查看:32
本文介绍了如何为标有自定义注释的属性调用 getter/setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在创建用于解析 Excel 文件的自定义编组工具.我想知道如何首先找到带有自定义注释的所有属性(这需要考虑继承,所以不仅仅是 getDeclaredFields),然后根据我使用的方法调用相应的 getter 或 setter.现在,我只关注二传手.

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.

当前代码:

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

示例类:

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

推荐答案

您可以使用反射来调用这些方法.

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

这篇关于如何为标有自定义注释的属性调用 getter/setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆