Java—自定义注解的实现

2019-05-09  本文已影响0人  东方未曦

一、关于注解

注解是Java中的一个常见特性,如果当前类继承自某个父类或者实现了某个接口,那么继承(实现)的方法上会包含一个@override注解,表示当前这个方法重写了父类或者接口的方法。@override注解的功能比较简单,只是让开发人员意识到当前方法是重写的,该注解在编译时就会被丢弃。而平时我们所使用的一些框架内的注解都是需要在运行时获得其注解的类或对象的,因此级别与override注解不同。

二、 元注解

自定义注解时,需要使用元注解对自定义注解进行修饰,因此元注解就是修饰注解的注解。Java提供的4种元注解如下:

注解 作用 属性 取值
@Target 标识注解所使用的范围 ElementType CONSTRUCTOR:构造器的声明
FIELD:域声明(包括enum实例)
LOCAL_VARIABLE:局部变量声明
METHOD:方法声明
PACKAGE:包声明
PARAMETER:参数声明
TYPE:类、接口(包括注解类型)或enum声明
@Retention 表示需要在什么级别保存该注解信息 RetentionPolicy SOURCE:注解将被编译器丢弃
CLASS:注解在class文件中可用,但会被虚拟机丢弃
RUNTIME:虚拟机将在运行期间保留注解,因此可以通过反射机制读取注解的信息
@Document 在javadoc中包含注解
@Inherited 允许子类继承该注解

三、注解的实现与应用

自定义注解一般为运行时注解,通过反射找到添加该注解的类、方法或属性,然后根据注解中的字段取值判断该类或方法是否符合标准。
注解中的参数支持以下类型及其数组,注解的参数必须有确定的默认值,要么在定义时给定,要么在使用注解时给定。

1. 基本类型:byte, short, char, int, long, float, double
2. String
3. Class
4. enum
5. Annotation

通过反射获取注解上的类、方法和属性时,主要使用以下方法。

1. 判断该元素是否被annotationClass注解修饰
boolean is AnnotationPresent(Class<?extends Annotation> annotationClass)
2. 获取 该元素上annotationClass类型的注解,如果没有返回null
<T extends Annotation> T getAnnotation(Class<T> annotationClass)
3. 返回该元素上所有的注解
Annotation[] getAnnotations()
4. 返回该元素上指定类型所有的注解
<T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass)
5. 返回直接修饰该元素的所有注解
Annotation[] getDeclaredAnnotations()
6. 返回直接修饰该元素的所有注解
<T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass)

3.1 实例:通过注解表示任务

这是一个经典的例子,在某个方法上添加注解,标注该方法的优先级和完成度,随后可以通过反射获取到这些方法的优先级信息。
注解定义如下,这是一个添加在方法上的注解,属性包括作者、优先级和状态,并为每个属性定义了一个默认值。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Todo {
    public enum Priority {LOW, MEDIUM, HIGH}
    public enum Status {STARTED, NOT_STARTED}    
    String author() default "Author";
    Priority priority() default Priority.LOW;
    Status status() default Status.NOT_STARTED;
}

随后为工作类中的方法添加注解,标明其优先级和进度。

public class BusinessLogic {
    public BusinessLogic() {
        super();
    }
    
    @Todo(priority = Todo.Priority.HIGH)
    public void notYetStartedMethod() {
    }
    
    @Todo(priority = Todo.Priority.MEDIUM, author = "Uday", status = Todo.Status.STARTED)
    public void incompleteMethod1() {
    }

    @Todo(priority = Todo.Priority.LOW, status = Todo.Status.STARTED )
    public void incompleteMethod2() {
    }
}

通过反射取出某个类中所有带有该注解的方法。

Class businessLogicClass = BusinessLogic.class;
for(Method method : businessLogicClass.getMethods()) {
Todo todoAnnotation = (Todo)method.getAnnotation(Todo.class);
    if(todoAnnotation != null) {
        System.out.println(" Method Name : " + method.getName());
        System.out.println(" Author : " + todoAnnotation.author());
        System.out.println(" Priority : " + todoAnnotation.priority());
        System.out.println(" Status : " + todoAnnotation.status());
    }
}

3.2 实例:通过注解判断属性是否符合要求

上面介绍了注解在方法上的应用,这里介绍一个注解在类和属性上的结合应用。主要通过注解来判断当前实体类中String的长度是否符合标准。
首先需要定义在类和属性上的2个注解。
实体类注解:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface EntityCheck {
    
    String entityName();
    
}

属性注解:

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldCheck {
    
    int min() default 0;
    int max() default 0;
    String error();
    
}

使用注解时分别在实体类以及实体类中需要进行长度限制的String字段上进行注解。当字段的长度与期望不符时,通过error进行提示。

@EntityCheck(entityName = "Entity")
public class Entity {
    
    @FieldCheck(min = 4, max = 10, error = "f1 not in range")
    private String field1;
    
    @FieldCheck(min = 8, max = 12, error = "f2 not in range")
    private String field2;
    
    public Entity(String f1, String f2) {
        field1 = f1;
        field2 = f2;
    }
    
}

注解的解析如下,方法传入Object,得到Class对象后判断其是否被EntityCheck所注解,如果注解则认为该类是实体类,并对其被FieldCheck注解的字段进行判断,如果不符合,则输出error信息。

public class EntityTestUtils {
    
    public void check(Object o) throws Exception {
        Class c = o.getClass();
        // 如果当前的类被 @Entity 注解
        if (c.isAnnotationPresent(EntityCheck.class)) {
            Field[] fields = c.getDeclaredFields();
            for (Field field : fields) {
                // 如果当前 field 被 @FieldCheck 注解
                if (field.isAnnotationPresent(FieldCheck.class)) {
                    field.setAccessible(true);
                    FieldCheck fieldCheck = field.getAnnotation(FieldCheck.class);
                    if (field.getGenericType().toString().equals("class java.lang.String")) {
                        String s = (String) field.get(o);
                        if (s != null && 
                                (s.length() < fieldCheck.min() || s.length() > fieldCheck.max())) {
                            System.out.println(fieldCheck.error());
                        }
                    }
                }
            }
        }
    }
    
    public static void main(String[] args) {
        EntityTestUtils entityTestUtils = new EntityTestUtils();
        Entity entity = new Entity("12", "12");
        try {
            entityTestUtils.check(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

结果如下:

f1 not in range
f2 not in range

这里进行测试时传入了Entity对象,其实任何注解了EntityCheck的类的对象都可以作为输入,注解的松耦合性给编程带来了极大的便利。
有些数据库框架通过注解来生成SQL语句,感兴趣的同学可以实践一下。

上一篇 下一篇

猜你喜欢

热点阅读