java注解详解

一,基本语法
首先,我们先来定义一个最简单的没有元素的注解,称为标记注解。

  @Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.METHOD)
  public @interface Test {
  }

它就像一个空接口。定义注解时会需要一些元注解。@Retention用来定义该注解在哪一个级别可用,在源代码中(SOURCE),类文件中(CLASS),或者运行时(RUNTIME)。@Target用来定义你的注解用在什么地方(例如一个方法或者一个域。
下面再写一个有元素的简单注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UserCase {
    public int id();
    public String description() default "no description";
}

二,编写注解处理器
注解对语义没有直接的影响,它们只负责提供信息供相关的程序使用。注解永远不会改变被注解代码的语义。我们需要编写注解处理器来为注解添加相应的逻辑。
我们在日常项目的开发中,不得不处理的就是异常。我们需要编写一个异常处理器来对异常进行相应的处理。

首先,编写一个注解,参数类型为Class对象的数组。

   @Retention(RetentionPolicy.RUNTIME)
   @Target(ElementType.METHOD)
    public @interface ExceptionTest {
        Class[] value();
    }

再编写一个注解处理器

public static void test(Class testClazz) {
        for (Method m : testClazz.getDeclaredMethods()) {
            if (m.isAnnotationPresent(ExceptionTest.class)) {
                try {
                    m.invoke(testClazz.newInstance());
                } catch (Throwable wrappedExc) {
                    Class[] excTypes = m.getAnnotation(ExceptionTest.class).value();
                    for(Class excType : excTypes){
                        if(excType.isInstance(wrappedExc)){
                            System.out.println("处理相应逻辑");
                        }
                    }

                }
            }
        }

你可能感兴趣的:(java基础)