转载自(https://www.cnblogs.com/liangweiping/p/3837332.html)
目录
1.通过自定义注解,进行赋值
2.通过自定义注解,进行校验
3.实际应用如何应用自定义注解
4.其他注意事项
-----------------------------
1.通过自定义注解,进行赋值
1.自定义注解

1package annotation; 2 3import java.lang.annotation.Documented; 4import java.lang.annotation.ElementType; 5import java.lang.annotation.Inherited; 6import java.lang.annotation.Retention; 7import java.lang.annotation.RetentionPolicy; 8import java.lang.annotation.Target; 9 10/** 11 * Init.java 12 * 13 * @author IT唐伯虎 2014年7月10日 14 */ 15@Documented 16@Inherited 17@Target({ ElementType.FIELD, ElementType.METHOD }) 18@Retention(RetentionPolicy.RUNTIME) 19public @interface Init 20{ 21 public String value() default ""; 22}

2.在数据模型使用注解

1package model; 2 3import annotation.Init; 4 5/** 6 * User.java 7 * 8 * @author IT唐伯虎 2014年7月10日 9 */ 10public class User 11{ 12 private String name; 13 private String age; 14 15 public String getName() 16 { 17 return name; 18 } 19 20 @Init(value = "liang") 21 public void setName(String name) 22 { 23 this.name = name; 24 } 25 26 public String getAge() 27 { 28 return age; 29 } 30 31 @Init(value = "23") 32 public void setAge(String age) 33 { 34 this.age = age; 35 } 36}

3.用“构造工厂”充当“注解解析器”

1package factory; 2 3import java.lang.reflect.Method; 4 5import annotation.Init; 6import model.User; 7 8/** 9 * UserFactory.java 10 * 11 * @author IT唐伯虎 2014年7月10日 12 */ 13public class UserFactory 14{ 15 public static User create() 16 { 17 User user = new User(); 18 19 // 获取User类中所有的方法(getDeclaredMethods也行) 20 Method[] methods = User.class.getMethods(); 21 22 try 23 { 24 for (Method method : methods) 25 { 26 // 如果此方法有注解,就把注解里面的数据赋值到user对象 27 if (method.isAnnotationPresent(Init.class)) 28 { 29 Init init = method.getAnnotation(Init.class); 30 method.invoke(user, init.value()); 31 } 32 } 33 } 34 catch (Exception e) 35 { 36 e.printStackTrace(); 37 return null; 38 } 39 40 return user; 41 } 42}

4.运行的代码

1package app; 2 3import java.lang.reflect.InvocationTargetException; 4 5import factory.UserFactory; 6import model.User; 7 8/** 9 * Test.java 10 * 11 * @author IT唐伯虎 2014年7月10日 12 */ 13public class Test 14{ 15 public static void main(String[] args) throws IllegalAccessException, 16 IllegalArgumentException, InvocationTargetException 17 { 18 User user = UserFactory.create(); 19 20 System.out.println(user.getName()); 21 System.out.println(user.getAge()); 22 } 23}

5.运行结果
1liang 223
2.通过自定义注解,进行校验
1.自定义注解

1package annotation; 2 3import java.lang.annotation.Documented; 4import java.lang.annotation.ElementType; 5import java.lang.annotation.Inherited; 6import java.lang.annotation.Retention; 7import java.lang.annotation.RetentionPolicy; 8import java.lang.annotation.Target; 9 10/** 11 * Validate.java 12 * 13 * @author IT唐伯虎 2014年7月11日 14 */ 15@Documented 16@Inherited 17@Target({ ElementType.FIELD, ElementType.METHOD }) 18@Retention(RetentionPolicy.RUNTIME) 19public @interface Validate 20{ 21 public int min() default 1; 22 23 public int max() default 10; 24 25 public boolean isNotNull() default true; 26}

2.在数据模型使用注解

1package model; 2 3import annotation.Validate; 4 5/** 6 * User.java 7 * 8 * @author IT唐伯虎 2014年7月11日 9 */ 10public class User 11{ 12 @Validate(min = 2, max = 5) 13 private String name; 14 15 @Validate(isNotNull = false) 16 private String age; 17 18 public String getName() 19 { 20 return name; 21 } 22 23 public void setName(String name) 24 { 25 this.name = name; 26 } 27 28 public String getAge() 29 { 30 return age; 31 } 32 33 public void setAge(String age) 34 { 35 this.age = age; 36 } 37}

3.注解解析器

1package check; 2 3import java.lang.reflect.Field; 4 5import annotation.Validate; 6import model.User; 7 8/** 9 * UserCheck.java 10 * 11 * @author IT唐伯虎 2014年7月11日 12 */ 13public class UserCheck 14{ 15 public static boolean check(User user) 16 { 17 if (user == null) 18 { 19 System.out.println("!!校验对象为空!!"); 20 return false; 21 } 22 23 // 获取User类的所有属性(如果使用getFields,就无法获取到private的属性) 24 Field[] fields = User.class.getDeclaredFields(); 25 26 for (Field field : fields) 27 { 28 // 如果属性有注解,就进行校验 29 if (field.isAnnotationPresent(Validate.class)) 30 { 31 Validate validate = field.getAnnotation(Validate.class); 32 if (field.getName().equals("age")) 33 { 34 if (user.getAge() == null) 35 { 36 if (validate.isNotNull()) 37 { 38 System.out.println("!!年龄可空校验不通过:不可为空!!"); 39 return false; 40 } 41 else 42 { 43 System.out.println("年龄可空校验通过:可以为空"); 44 continue; 45 } 46 } 47 else 48 { 49 System.out.println("年龄可空校验通过"); 50 } 51 52 if (user.getAge().length() < validate.min()) 53 { 54 System.out.println("!!年龄最小长度校验不通过!!"); 55 return false; 56 } 57 else 58 { 59 System.out.println("年龄最小长度校验通过"); 60 } 61 62 if (user.getAge().length() > validate.max()) 63 { 64 System.out.println("!!年龄最大长度校验不通过!!"); 65 return false; 66 } 67 else 68 { 69 System.out.println("年龄最大长度校验通过"); 70 } 71 } 72 if (field.getName().equals("name")) 73 { 74 if (user.getName() == null) 75 { 76 if (validate.isNotNull()) 77 { 78 System.out.println("!!名字可空校验不通过:不可为空!!"); 79 return false; 80 } 81 else 82 { 83 System.out.println("名字可空校验通过:可以为空"); 84 continue; 85 } 86 } 87 else 88 { 89 System.out.println("名字可空校验通过"); 90 } 91 92 if (user.getName().length() < validate.min()) 93 { 94 System.out.println("!!名字最小长度校验不通过!!"); 95 return false; 96 } 97 else 98 { 99 System.out.println("名字最小长度校验通过"); 100 } 101 102 if (user.getName().length() > validate.max()) 103 { 104 System.out.println("!!名字最大长度校验不通过!!"); 105 return false; 106 } 107 else 108 { 109 System.out.println("名字最大长度校验通过"); 110 } 111 } 112 } 113 } 114 115 return true; 116 } 117}

4.运行的代码

1package app; 2 3import check.UserCheck; 4import model.User; 5 6/** 7 * Test.java 8 * 9 * @author IT唐伯虎 2014年7月11日 10 */ 11public class Test 12{ 13 public static void main(String[] args) 14 { 15 User user = new User(); 16 17 user.setName("liang"); 18 user.setAge("1"); 19 20 System.out.println(UserCheck.check(user)); 21 } 22}

5.运行结果

1名字可空校验通过 2名字最小长度校验通过 3名字最大长度校验通过 4年龄可空校验通过 5年龄最小长度校验通过 6年龄最大长度校验通过 7true

3.实际应用如何应用自定义注解
Q: 实际我们用的时候,比如校验,加上注解之后,我们给user对象set值,会自动校验,不会主动调用check方法,这部分是怎么个实现原理,楼主能否补充一下,谢谢?
A:实际项目中通过拦截器或者切面来实现:
1、定义一个interface,命名为BaseCheck,BaseCheck里面有一个抽象的check方法,check方法返回值是boolean。
2、定义校验的注解,比如:@NotNull、@Length。
3、根据上面的注解,分别定义对应的校验类,比如:NotNullCheck、LengthCheck。
4、NotNullCheck、LengthCheck都需要实现BaseCheck的check方法,你要在check方法里面写校验流程。
5、定义一个容器,在工程启动的时候,把NotNullCheck和LengthCheck的对象塞到里面,
如果你使用spring,直接在NotNullCheck和LengthCheck上面加个注解@Component,也能达到同样的效果。
6、定义一个拦截器或者切面。
7、在这个拦截器或者切面里,拿到请求的参数,也就是那个user对象。
8、通过反射,获取到这个user对象所对应的类,类的名字肯定就是User了。
9、遍历User里面的所有Field,检查每一个Field是否含有注解。
10、遍历Field上的所有注解。
11、假设找到一个注解@NotNull,就去找一下对应的校验类,
BaseCheck baseCheck = 容器.get("NotNullCheck")
或者BaseCheck baseCheck = (BaseCheck) SpringUtl.getBean("NotNullCheck")
12、如果找到,也就是baseCheck不为空,则通过反射获取这个Field的实际值,将这个值作为参数,调用baseCheck.check方法
13、baseCheck.check如果返回false则报错,如果返回true则继续,直到遍历完所有Field、所有注解
4.其他注意事项
1-如下定义,是spring中定义@Service注解,
意味着@Service 继承了 @Component注解的所有功能
