自定义注解判空简单示例

不说废话,上主代码:

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import a.jery.NotNull;

public final class Demo {    
    public static void main(String[] args) {        
        Person p=new Person();
        p.setPersonName("123");
        CheckRS rs=check(p);
        System.out.println(String.format("flag:%s,msg:%s.", rs.getFlag(),rs.getMsg()));
        p.setPersonName(null);
        rs=check(p);
        System.out.println(String.format("flag:%s,msg:%s.", rs.getFlag(),rs.getMsg()));
        System.exit(0);
    }
    
    @SuppressWarnings({ "rawtypes"})
    public static CheckRS check(Object param){
        CheckRS rs=new CheckRS();
        Class cls=param.getClass();
        try {            
            BeanInfo beanInfo=Introspector.getBeanInfo(cls);
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            for(PropertyDescriptor pd:pds){
                Method readMethod=pd.getReadMethod();
                Method writeMethod=pd.getWriteMethod();
                if(null!=readMethod&&null!=writeMethod){
                    Field field=cls.getDeclaredField(pd.getName());
                    if(null!=field&&null!=field.getAnnotation(NotNull.class)){
                        if(null==readMethod.invoke(param)){
                            rs.setFlag(false);
                            rs.setMsg(field.getAnnotation(NotNull.class).value());
                            break;
                        }                        
                    }
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rs;
    }
    
}

运行结果:

flag:true,msg:null.
flag:false,msg:姓名不可为空.

自定义注解类:

package a.jery;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({java.lang.annotation.ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNull {
    String value() default "NotNull.value";
}

普通类:

  

import a.jery.NotNull;


public class Person {    
    
    @NotNull("姓名不可为空")
    private String personName;

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }    

}

至此 演示完毕。

转载于:https://www.cnblogs.com/shoubianxingchen/p/5722761.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值