来自对codeSheep的总结
1.注解是什么:
注解是写给程序看的(类似于标签),注释写给人看的。
2.出现的位置:
类、方法、变量、接口、形参位置等。
3.注解分类:
自定义注解、JDK内置注解、还有第三方框架提供的注解。
4.注解的作用:
让代码更加简洁。代码生成,数据校验,资源整合等。
5.手写一个注解:
如果没有注解,想要校验,我们只能通过手写if来判断。
①定义注解:@Length
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Length {
int min(); //允许字符串长度的最小值
int max(); //允许字符串长度的最大值
String errorMsg(); //自定义的错误提示信息
}
②获取注解并对其进行验证
public class TestAnno {
private Long id;
private String name;
@Length(min=11, max=11, errorMsg = "错误,电话号码的长度必须为11位")
private String mobile;//手机号码(11位)
public static String validate(Object object) throws IllegalAccessException {
//首先通过反射获取object对象的类有哪些字段
//对本文来说就可以获取到student类的id、name、mobile字段
Field[] fields =object.getClass().getDeclaredFields();
//for循环逐个字段校验,看哪个字段上标记了注解。
for (Field field : fields){
//if判断:检查该字段上y有没有标记了Length注解
if (field.isAnnotationPresent(Length.class)){
//通过反射获取到该字段上标注的@Length注解的详细信息
Length length=field.getAnnotation(Length.class);
field.setAccessible(true);//反射时能访问到私有变量
//用过反射获取字段的实际值
int value=( (String) field.get(object)).length();
//将字段的实际值和注解上做标示的值进行对比
if (value<length.min() || value>length.max()){
return length.errorMsg();
}
}
}
return "符合标准";
}
public static void main(String[] args) throws Exception{
TestAnno ta = new TestAnno();
//设置一个不符合条件的值进行验证
ta.mobile="123456";
String test = ta.validate(ta);
System.out.println(test);
}
}