java 实现自动校验必传参数

一、创建一个自定义注解

import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.METHOD})
@Documented
public @interface IsItNecessary {
boolean key() default false;
}

二、建立一个实体类

@IsItNecessary(key =true)        //必传参数 private String mappingId; @IsItNecessary(key =true) private String companyId; private String membershipCard; private String membershipCardNum; private String userName; @IsItNecessary(key =true) private String mobilePhone;
private String mappingId;
@IsItNecessary(key =true)
private String companyId;
private String membershipCard;
private String membershipCardNum;
private String userName;
@IsItNecessary(key =true)
private String mobilePhone;

三、通过java反射拿到实体类参数

public static void  isAllFieldNull(Object obj) throws Exception{
        Class stuCla = (Class) obj.getClass();// 得到类对象
        Field[] fs = stuCla.getDeclaredFields();//得到属性集合
        boolean flag = true;
        boolean r =false;
        for (Field f : fs) {//遍历属性
            f.setAccessible(true); // 设置属性是可以访问的(私有的也可以)
            Object val = f.get(obj);// 得到此属性的值

            IsItNecessary t = (IsItNecessary) f.getAnnotation(IsItNecessary.class);

            if(t != null) {
                r = t.key();

                if (r == false) {
                    continue;
                }

                if (val != null) {//只要有1个属性不为空,那么就不是所有的属性值都为空
                    System.out.println("属性" + f.getName() + "值为:" + val);
                } else {
                    System.out.println("属性" + f.getName() + ",不能为空");
                }
            }
        }
    }

最后测试

    public static void main( String[] args ) {
        GsUser gsUser = new GsUser();

        try {
            isAllFieldNull(gsUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
      
    }
运行结果:



未完待续!!!!

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值