基于注解的参数校验

 

一、编写自定义注解
package com.test;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到  
@Target({ElementType.FIELD,ElementType.METHOD})//定义注解的作用目标**作用范围字段、枚举的常量/方法  
@Documented//说明该注解将被包含在javadoc中  
public @interface AbNotNull {

	String message() default "字段不能为空";
}

package com.test;

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

@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到  
@Target({ElementType.FIELD,ElementType.METHOD})//定义注解的作用目标**作用范围字段、枚举的常量/方法  
@Documented//说明该注解将被包含在javadoc中  
public @interface AbNotEmpty {

	String message() default "字段不能为空";
}


package com.test;

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

@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到  
@Target({ElementType.FIELD,ElementType.METHOD})//定义注解的作用目标**作用范围字段、枚举的常量/方法  
@Documented//说明该注解将被包含在javadoc中  
public @interface AbLength {
	
	/**
	 * 最小长度
	 * @return
	 */
	int min() default 0;
	
	/**
	 * 最大长度
	 * @return
	 */
	int max() default Integer.MAX_VALUE;
	
	/**
	 * 提示信息
	 * @return
	 */
	String message() default "字段长度不符合要求";
}
二、编写校验器
package com.test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

public class AbValidateUtils {

	private static final String functionPre = "check";
	
	public static void validate(Object bean){
		Class<?> objectClass = bean.getClass();
		// 检测field是否存在  
        try {  
            // 获取实体字段集合  
            Field[] fields = objectClass.getDeclaredFields();  
            for (Field f : fields) {  
                // 通过反射获取该属性对应的值  
                f.setAccessible(true);  
                // 获取字段值  
                Object value = f.get(bean);  
                // 获取字段上的注解集合  
                Annotation[] arrayAno = f.getAnnotations();  
                for (Annotation annotation : arrayAno) {  
                	Object abValidateUtils = AbValidateUtils.class.newInstance();
                	// 根据方法名获取该方法  
                    Method m = abValidateUtils.getClass().getDeclaredMethod(functionPre + annotation.annotationType().getSimpleName().substring(2),Annotation.class, Object.class, Field.class);  
                    m.invoke(abValidateUtils,annotation, value, f);
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
	}
	
	@SuppressWarnings("unused")
	private void checkNotNull(Annotation annotation,Object value, Field field){
		AbNotNull abNotNull = (AbNotNull) annotation;
		if(null == value){
			System.out.println("校验失败:" +field.getName() +" "+ abNotNull.message());
		}
	}
	
	@SuppressWarnings({ "unused", "rawtypes" })
	private void checkNotEmpty(Annotation annotation,Object value, Field field){
		AbNotEmpty abNotEmpty = (AbNotEmpty) annotation;
		if(null == value){
			System.out.println("校验失败:" +field.getName() +" "+ abNotEmpty.message());
		}else if(value instanceof String && value.toString().trim().equals("")){
			System.out.println("校验失败:" +field.getName() +" "+ abNotEmpty.message());
		}else if(value instanceof List && (((List) value).size() == 0)){
			System.out.println("校验失败:" +field.getName() +" "+ abNotEmpty.message());
		}else if(value instanceof Map && (((Map) value).size() == 0)){
			System.out.println("校验失败:" +field.getName() +" "+ abNotEmpty.message());
		}
	}
	
	@SuppressWarnings("unused")
	private void checkLength(Annotation annotation,Object value, Field field){
		AbLength abLength = (AbLength) annotation;
		if(null == value || value.toString().length()< abLength.min() || value.toString().length()>abLength.max()){
			System.out.println("校验失败:" +field.getName() +" "+ abLength.message());
		}
	}
}
三、执行校验
package com.test;

import java.util.ArrayList;
import java.util.List;

public class AbValidateUtilsTest {

	public static void main(String[] args) {
		SysUser sysUser = new SysUser();
		//sysUser.setUserName("发生的发阿斯蒂芬是否阿萨德发送到发送到发送到发生发是否阿萨德发生的发阿斯蒂芬阿斯蒂芬阿斯蒂芬是否按时防撒旦发送的发sad");
		List<String> tele = new ArrayList<>();
		tele.add("d");
		sysUser.setTele(tele);
		AbValidateUtils.validate(sysUser);
	}
}

 

转载于:https://my.oschina.net/fellowtraveler/blog/892427

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值