Java自定义注解
前言:这两天看了一下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
7.注解解析器:用来解析自定义注解。
二、通过注解进行赋值(结合了工厂方法模式)
1.自定义注解
packageannotation; importjava.lang.annotation.Documented; importjava.lang.annotation.ElementType; importjava.lang.annotation.Inherited; importjava.lang.annotation.Retention; importjava.lang.annotation.RetentionPolicy; importjava.lang.annotation.Target; @Documented @Inherited @Target({ElementType.FIELD,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public@interfaceInit { publicStringvalue()default""; }2.在数据模型使用注解
packagemodel; importannotation.Init; publicclassUser { privateStringname; privateStringage; publicStringgetName() { returnname; } @Init(value="liang") publicvoidsetName(Stringname) { this.name=name; } publicStringgetAge() { returnage; } @Init(value="23") publicvoidsetAge(Stringage) { this.age=age; } }3.用“构造工厂”充当“注解解析器”
packagefactory; importjava.lang.reflect.Method; importannotation.Init; importmodel.User; publicclassUserFactory { publicstaticUsercreate() { Useruser=newUser(); //获取User类中所有的方法(getDeclaredMethods也行) Method[]methods=User.class.getMethods(); try { for(Methodmethod:methods) { //如果此方法有注解,就把注解里面的数据赋值到user对象 if(method.isAnnotationPresent(Init.class)) { Initinit=method.getAnnotation(Init.class); method.invoke(user,init.value()); } } } catch(Exceptione) { e.printStackTrace(); returnnull; } returnuser; } }4.运行的代码
packageapp; importjava.lang.reflect.InvocationTargetException; importfactory.UserFactory; importmodel.User; publicclassTest { publicstaticvoidmain(String[]args)throwsIllegalAccessException, IllegalArgumentException,InvocationTargetException { Useruser=UserFactory.create(); System.out.println(user.getName()); System.out.println(user.getAge()); } }5.运行结果
liang 23三、通过注解进行校验
1.自定义注解
packageannotation; importjava.lang.annotation.Documented; importjava.lang.annotation.ElementType; importjava.lang.annotation.Inherited; importjava.lang.annotation.Retention; importjava.lang.annotation.RetentionPolicy; importjava.lang.annotation.Target; @Documented @Inherited @Target({ElementType.FIELD,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public@interfaceValidate { publicintmin()default1; publicintmax()default10; publicbooleanisNotNull()defaulttrue; }2.在数据模型使用注解
packagemodel; importannotation.Validate; publicclassUser { @Validate(min=2,max=5) privateStringname; @Validate(isNotNull=false) privateStringage; publicStringgetName() { returnname; } publicvoidsetName(Stringname) { this.name=name; } publicStringgetAge() { returnage; } publicvoidsetAge(Stringage) { this.age=age; } }3.注解解析器
packagecheck; importjava.lang.reflect.Field; importannotation.Validate; importmodel.User; publicclassUserCheck { publicstaticbooleancheck(Useruser) { if(user==null) { System.out.println("!!校验对象为空!!"); returnfalse; } //获取User类的所有属性(如果使用getFields,就无法获取到private的属性) Field[]fields=User.class.getDeclaredFields(); for(Fieldfield:fields) { //如果属性有注解,就进行校验 if(field.isAnnotationPresent(Validate.class)) { Validatevalidate=field.getAnnotation(Validate.class); if(field.getName().equals("age")) { if(user.getAge()==null) { if(validate.isNotNull()) { System.out.println("!!年龄可空校验不通过:不可为空!!"); returnfalse; } else { System.out.println("年龄可空校验通过:可以为空"); continue; } } else { System.out.println("年龄可空校验通过"); } if(user.getAge().length()<validate.min()) { System.out.println("!!年龄最小长度校验不通过!!"); returnfalse; } else { System.out.println("年龄最小长度校验通过"); } if(user.getAge().length()>validate.max()) { System.out.println("!!年龄最大长度校验不通过!!"); returnfalse; } else { System.out.println("年龄最大长度校验通过"); } } if(field.getName().equals("name")) { if(user.getName()==null) { if(validate.isNotNull()) { System.out.println("!!名字可空校验不通过:不可为空!!"); returnfalse; } else { System.out.println("名字可空校验通过:可以为空"); continue; } } else { System.out.println("名字可空校验通过"); } if(user.getName().length()<validate.min()) { System.out.println("!!名字最小长度校验不通过!!"); returnfalse; } else { System.out.println("名字最小长度校验通过"); } if(user.getName().length()>validate.max()) { System.out.println("!!名字最大长度校验不通过!!"); returnfalse; } else { System.out.println("名字最大长度校验通过"); } } } } returntrue; } }4.运行的代码
packageapp; importcheck.UserCheck; importmodel.User; publicclassTest { publicstaticvoidmain(String[]args) { Useruser=newUser(); user.setName("liang"); user.setAge("1"); System.out.println(UserCheck.check(user)); } }5.运行结果
名字可空校验通过 名字最小长度校验通过 名字最大长度校验通过 年龄可空校验通过 年龄最小长度校验通过 年龄最大长度校验通过 true本文内容总结:
原文链接:https://www.cnblogs.com/liangweiping/p/3837332.html