如何为标有自定义注释的属性调用 getter/setter?

编程入门 行业动态 更新时间:2024-10-11 15:17:09
本文介绍了如何为标有自定义注释的属性调用 getter/setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我目前正在创建用于解析 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-20 20:46:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/988674.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   注释   何为   标有   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!