Java中自定义注解实现

一、问题描述

自定义注解实现对对象中姓名不能为空,年龄不能小于18大于25。

二、分析

由问题知,可以分别创建两个注解来验证字符串已经整型,代表姓名与年龄的验证。

三、代码实现

1.创建字符串验证注解

package work12_2022_12_09;

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

import org.junit.jupiter.api.Tag;

@Target({ElementType.LOCAL_VARIABLE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface StringUtil {
	
	
	//设置默认参数
	int maxLength() default Integer.MAX_VALUE;
	int minLength() default 0;
	String msg() default "字符串格式错误";
	String msgNull() default "字符串不能为空";
	

}

2.创建年龄验证注解

package work12_2022_12_09;

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

@Target({ElementType.LOCAL_VARIABLE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AgeUtil {
	
	int minAge() default 0;//默认最小年龄
	int maxAge() default 100;//默认最大年龄
	String msg() default "年龄超出规定范围";

}

3.创建一个学生类

package work12_2022_12_09;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;


/*
 * 定义一个学生类
 * */
public class Student {
	
	//为字段添加自定义注解
	@StringUtil(minLength = 2,maxLength = 16)
	private String userName;
	
	@StringUtil(minLength = 2,maxLength = 16)
	private String password;
	
	@AgeUtil(maxAge = 25,minAge = 18)
	private Integer Age;


	public String getUserName() {
		return userName;
	}


	public void setUserName(String userName) {
		this.userName = userName;
	}


	public String getPassword() {
		return password;
	}


	public void setPassword(String password) {
		this.password = password;
	}


	public Integer getAge() {
		return Age;
	}


	public void setAge(Integer age) {
		Age = age;
	}


	public Student(String userName, String password, Integer age) {
		super();
		this.userName = userName;
		this.password = password;
		Age = age;
	}
	
	//验证方法
	public void validate(Student student) {		
		Class class1 = student.getClass();//获取当前需要验证的对象类
		Field[] fields = class1.getDeclaredFields();//获取类中字段
		for (Field field : fields) {//遍历字段
			
			//获取字段相对应的注解
			StringUtil stringUtil = field.getAnnotation(StringUtil.class);
			AgeUtil ageUtil = field.getAnnotation(AgeUtil.class);
			
			//开始验证
			if(stringUtil != null) {
				try {
					Object object = field.get(student);//获取字段
					if(object instanceof String) {//验证字段类型
						String str = (String)object;//若当前属性类型匹配则强制转换
						if(str.equals("")) {//判断是否为空
							throw new IllegalArgumentException(field.getName() + ":" + stringUtil.msgNull());
						}else {
							//验证长度
							int len = str.length();
							if(len < stringUtil.minLength() || len > stringUtil.maxLength()) {
								throw new IllegalArgumentException(field.getName() + ":" + stringUtil.msg());
							}
						}
					}
				} catch (IllegalArgumentException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}

			if(ageUtil != null) {
				try {
					Object object = field.get(student);
					if(object instanceof Integer) {
						Integer age = (Integer)object;
						if(age < ageUtil.minAge() || age > ageUtil.maxAge()) {
							throw new IllegalArgumentException(field.getName() + ":" + ageUtil.msg());
						}
					}
				} catch (IllegalArgumentException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
			
		}
	}


	@Override
	public String toString() {
		return "Student [userName=" + userName + ", password=" + password + ", Age=" + Age + "]";
	}


	
	
	

}

4.创建测试类

package work12_2022_12_09;

public class Test1 {

	
	public static void main(String[] args) {
		//测试数据1
		Student student = new Student("zhangsan", "123456", 15);
		
//		//测试数据2
//		Student student = new Student("kkklkjghgdfadsfdsg1234553", "123456", 25);
//		
//		//测试数据3
//		Student student = new Student("zhangsan", "", 20);
//		
//		//测试数据4
//		Student student = new Student("zhangsan", "123456", 20);
		
		student.validate(student);
		
		student.toString();
	}
}

四、测试

1.测试字符串长度

 

2.测试字符串是否为空

 

3.测试年龄是否正确

 

4.测试正确输入

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值