如何编写自定义注解

在Controller中经常需要对前台入参进行一些校验,用自定义注解可方便的实现,详细见如下代码

/**
 * 自定义注解
 * @author win 10
 *
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNull {
	String message();
}

自定义异常类用来辅助校验器抛出校验参数的异常信息在这里插入代码片

/**
 * 自定义异常类
 * @author win 10
 *
 */
public class CustomerException extends RuntimeException{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public CustomerException() {
		super();
	}
	
	public CustomerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}
	
	public CustomerException(String message, Throwable cause) {
		super(message, cause);
	}

	public CustomerException(String message) {
		super(message);
	}

	public CustomerException(Throwable cause) {
		super(cause);
	}
}

注解校验器,主要是通过反射动态的去获取对象的属性值

/**
 * 注解逻辑类
 * @author win 10
 *
 */
public class NotNullValidator {
	public static <T> void validator(T t) throws IllegalArgumentException, IllegalAccessException{
		boolean isThrowException = false;
		StringBuilder errorMessage = new StringBuilder();
		Class<? extends Object> cla = t.getClass();
		//利用反射获取类的所有字段包含私有属性
		Field[] fields = cla.getDeclaredFields();
		for(Field f:fields){
			//判断字段是否有定义NotNull注解
			NotNull notNullAnnotation = f.getAnnotation(NotNull.class);
			if(null != notNullAnnotation){
				f.setAccessible(true); //设置些属性是可以访问的
		        Object val = f.get(t);//得到此属性的值
		        boolean flag = notNull(val);
		        if(!flag){
		        	//获取注解上的异常信息
		        	errorMessage.append(notNullAnnotation.message()).append(",");
		        	isThrowException = true;
		        }
			}
		}
		if(isThrowException){
			exceptionMessage(errorMessage.toString());
		}
	}
	
	/**
	 * 判断字段类型以及值是否空
	 * @param value
	 * @return
	 */
	public static boolean notNull(Object value) {
		if(null == value) {
			return false;
		}
		if(value instanceof String && isEmpty(value.toString())) {
			return false;
		}
		if(value instanceof Integer && isEmpty((Integer)value)) {
			return false;
		}
		if(value instanceof List && isEmpty((List<?>) value)) {
			return false;
		}
		return null != value;
	}

	public static boolean isEmpty(String str) {
		return null == str || str.isEmpty();
	}
	
	public static boolean isEmpty(List<?> list) {
		return null == list || list.isEmpty();
	}
	
	public static boolean isEmpty(Integer i){
		return null == i;
	}
	/**
	 * 抛出注解对应的异常信息
	 * @param errorMessage
	 */
	public static void exceptionMessage(String errorMessage) {
		throw new CustomerException(errorMessage);
	}
}

实体类

public class Person {
	@NotNull(message = "姓名不能为空")
	private String name;
	
	@NotNull(message = "年龄不能为空")
	private Integer age;
	
	private Double salary;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Double getSalary() {
		return salary;
	}
	public void setSalary(Double salary) {
		this.salary = salary;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", salary=" + salary + "]";
	}
}

测试类

public class Test {
	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
		Person p = new Person();
		p.setSalary(12000d);
		NotNullValidator.validator(p);
		System.out.println(p);
	}
}

若需要校验参数其它合法性,可编写一个注解校验器,将所有的注解逻辑实现类放到校验器中,进行统一的校验。
以上代码亲测可用!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值