Java自定义注解实现验证实体类属性的合法性

一、注解的基础

1.注解的定义:Java文件叫做Annotation,用@interface表示。

2.元注解:@interface上面按需要注解上一些东西,包括@Retention、@Target、@Document、@Inherited四种。

3.注解的保留策略:

@Retention(RetentionPolicy.SOURCE) // 注解仅存在于源码中,在class字节码文件中不包含

@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得

@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到

4.注解的作用目标:

@Target(ElementType.TYPE) // 接口、类、枚举、注解

@Target(ElementType.FIELD) // 字段、枚举的常量

@Target(ElementType.METHOD) // 方法

@Target(ElementType.PARAMETER) // 方法参数

@Target(ElementType.CONSTRUCTOR) // 构造函数

@Target(ElementType.LOCAL_VARIABLE) // 局部变量

@Target(ElementType.ANNOTATION_TYPE) // 注解

@Target(ElementType.PACKAGE) // 包

5.注解包含在javadoc中:

@Documented

6.注解可以被继承:

@Inherited

1、自定义注解类:
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * 请求参数校验
 * @author Xuan
 *
 */
//注解包含于Javadoc中
@Documented
//注解的作用目标
@Target(ElementType.FIELD)
//注解可以被继承
@Inherited
//注解的保留策略
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNull {
	/**
	 * 必须参数
	 * @return
	 */
	boolean flag() default true;
}
2、实体类(规则需生成getandset方法):
import AnnotationResolve;

public class Pojo extends AnnotationResolve{
	
	@NotNull
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
3、自定义注解解析器:

import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
 * 自定义注解解析器
 * @author Xuan
 *
 */
public class AnnotationResolve {
	public boolean validate() throws NoSuchMethodException, SecurityException,Exception {
		// 获取类的属性
		Field[] fields = this.getClass().getDeclaredFields();
		for (Field field : fields) {
			System.out.println("1");
			if (field.isAnnotationPresent(NotNull.class)) {
				NotNull notnull = field
						.getAnnotation(NotNull.class);
				if (notnull.flag()) {
					// 如果类型是String
					// 如果type是类类型,则前面包含"class ",后面跟类名
					if (field.getGenericType().toString().equals("class java.lang.String")) { 
						// 拿到该属性的getet方法
						Method m = this.getClass().getMethod("get" + getMethodName(field.getName()));
						System.out.println(field.getName());
						// 调用getter方法获取属性值
						String val = (String) m.invoke(this);
						if (val == null || val.equals("")) {
							throw new Exception(field.getName() + " 不能为空!");
						}
						System.out.println("String t2ype:" + val);
					} else if (field.getGenericType().toString().equals("class java.lang.Integer")) {
						Method m = this.getClass().getMethod("get" + getMethodName(field.getName()));
						// 调用getter方法获取属性值
						Integer val = (Integer) m.invoke(this);
						if (val == null) {
							throw new Exception(field.getName() + " 不能为空!");
						}
						System.out.println("String ty1pe:" + val);
					}
				}
			}
		}
		return true;
	}
	
	/**
	 * 把一个字符串的第一个字母大写、效率是最高的
	 */
	private String getMethodName(String fildeName) throws Exception {
		byte[] items = fildeName.getBytes();
		items[0] = (byte) ((char) items[0] - 'a' + 'A');
		return new String(items);
	}
}
4、测试类:
public class test {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Pojo pojo = new Pojo();
		pojo.setName("轩");
		try {
			boolean flag =  pojo.validate();
			if(flag){
				System.out.println("验证通过");
			}else {
				System.out.println("验证失败");
			}
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
5、如下图:

在这里插入图片描述

  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个技术问题,我可以为您提供答案。 在 Java实现参数校验可以使用自定义注解来解决。您需要先定义一个注解类,例如通过 @NotNull 注解来表示参数不能为空。 然后在实体类中对需要进行校验的参数添加该注解,在业务逻辑中处理时就可以通过反射获取注解并进行校验。 以下是一个简单的示例代码: ``` @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface NotNull { String message() default "参数不能为空"; } public class User { @NotNull private String username; @NotNull private String password; // 省略其他属性及方法 } public class UserValidator { public static boolean validate(User user) { Field[] fields = user.getClass().getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(NotNull.class)) { field.setAccessible(true); try { Object value = field.get(user); if (value == null || "".equals(value)) { System.out.println("校验未通过:" + field.getAnnotation(NotNull.class).message()); return false; } } catch (Exception e) { e.printStackTrace(); return false; } } } System.out.println("校验通过"); return true; } } // 测试 public static void main(String[] args) { User user = new User(); user.setUsername(null); user.setPassword("password"); UserValidator.validate(user); } ``` 输出结果为: ``` 校验未通过:参数不能为空 ``` 这样可以方便地对实体类中的参数进行校验。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值