package com.moxi.mougblog.base.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
@Data
@Slf4j
public class IsEmptyUtil {
@ParamCheck(emptyAble = ParamCheck.CheckEnum.NOTEMPTY)
private String name;
//判断参数是否为空
public static boolean paramCheck(Object obj) {
try {
Class<?> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);//设置为true才可以访问私有变量
ParamCheck paramCheck = field.getAnnotation(ParamCheck.class);
if (paramCheck != null) {
if (paramCheck.emptyAble() == ParamCheck.CheckEnum.NOTEMPTY) {
Object val = field.get(obj);
if (val == null || "".equals(val.toString())) {
log.info(field.getName()+"是空的");
return false;
}
}
}
}
} catch (Exception ex) {
log.info("Param verify error");
return false;
}
return true;
}
public static void main(String[] args) {
new IsEmptyUtil().paramCheck(new IsEmptyUtil());
}
}
package com.moxi.mougblog.base.util;
import java.lang.annotation.*;
/**
* 参数校验注解
*
* @author yangyongjie
* @date 2020/5/14
* @desc
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ParamCheck {
/**
* 是否允许为空
*/
CheckEnum emptyAble() default CheckEnum.EMPTY;
enum CheckEnum {
NOTEMPTY,
EMPTY
}
}
获取属性的注解
public class TestAnnotation {
public static void main(String[] args){
try {
//获取Student的Class对象
Class stuClass = Class.forName("pojos.Student");
//说明一下,这里形参不能写成Integer.class,应写为int.class
Method stuMethod = stuClass.getMethod("study",int.class);
if(stuMethod.isAnnotationPresent(CherryAnnotation.class)){
System.out.println("Student类上配置了CherryAnnotation注解!");
//获取该元素上指定类型的注解
CherryAnnotation cherryAnnotation = stuMethod.getAnnotation(CherryAnnotation.class);
System.out.println("name: " + cherryAnnotation.name() + ", age: " + cherryAnnotation.age()
+ ", score: " + cherryAnnotation.score()[0]);
}else{
System.out.println("Student类上没有配置CherryAnnotation注解!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}