通过自定义注解与反射对特定属性赋值

  • 自定义注解
package com.yms.anno;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Indexed;

/**
 * @author yms
 * @description:
 * @date: 2021/9/17 9:48
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
@Component
@Indexed
public @interface OCRAnnotation {

  String value() default "";

  String name() default "";

  String code() default "";

}
  • 通过反射对该注解标注的属性进行赋值
package org.yms.test;

import com.yms.anno.OCRAnnotation;
import com.yms.ocr.OcrTicketVo;
import com.yms.ocr.OcrTrainTicketVo;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author yms
 * @description:
 * @date: 2021/9/17 18:19
 */
public class OCRTest {

  private OcrTicketVo setFields(Map<String,Object> trainMap){
    OcrTrainTicketVo train = new OcrTrainTicketVo();
    //getFields():获得某个类的所有的公共(public)的字段,包括父类中的字段。
    //getDeclaredFields():获得某个类的所有声明的字段,即包括public、private和proteced,但是不包括父类的申明字段。
    Field[] vatFields = train.getClass().getDeclaredFields();
    for (Field field : vatFields) {
      //判断该属性有没有被@OCRAnnotation标注
      if(field.isAnnotationPresent(OCRAnnotation.class)){
        String key = field.getAnnotation(OCRAnnotation.class).value();
        if(trainMap.containsKey(key)){
          field.setAccessible(true);
          try {
            field.set(train,trainMap.get(key));
          } catch (IllegalAccessException e) {
            e.printStackTrace();
          }
        }
      }
    }
    return train;
  }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值