自定义注解判空简单示例

时间:2021-08-29 20:35:57

不说废话,上主代码:

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;
    }    

}

至此 演示完毕。