JAVA根据对象属性名和对象实体获取对象中该属性名的某个注解

 

以下示例

/**
     * 根据属性名和类获取该属性上@ApiModelProperty注解的value值
     *
     * @param fieldName 属性名
     * @param clazz     类对象
     * @return 注解中的value值,如果不存在则返回null
     */
    public static String getApiModelPropertyValue(String fieldName, Class<?> clazz) {
        try {
            // 获取指定名称的字段
            Field field = clazz.getDeclaredField(fieldName);
            
            // 获取字段上的@ApiModelProperty注解
            ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
            
            // 如果注解存在,则返回其value值
            if (annotation != null) {
                return annotation.value();
            }
        } catch (NoSuchFieldException e) {
            log.warn("字段 {} 在类 {} 中未找到",fieldName,clazz.getSimpleName());
        }
        return null;
    }

 

posted @ 2025-11-14 09:51  yvioo  阅读(3)  评论(0)    收藏  举报