自定义注解

package AnnotationTest;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)         //retention 放弃;维持;保留@Target(ElementType.METHOD)public @interface MultiTest {       //@interface 注解标识   int a() default 0; //相似函数的模式定义变量   int b() default 0; //没有default就得传入参数}

测试

package AnnotationTest;public class Foo {    @MultiTest(a=1,b=1)    public static void m1(int a,int b){        if (a+b<0) throw new RuntimeException("Crash"); }    @MultiTest    public static void m2(int a,int b){        if (a+b<0) throw new RuntimeException("Broken"); }    @MultiTest(b=-2,a=1)        //多参数必须要指定给哪个变量赋值    public static void m3(int a,int b){        if (a+b<0) throw new RuntimeException("Boom"); }}

主函数

package AnnotationTest;import java.lang.reflect.Method;public class Main {    public static void main(String[] args) throws Exception {        int passed = 0,failed=0;        String className = "AnnotationTest.Foo"; //全门路        for (Method m : Class.forName(className).getMethods()) {    //获取办法            if (m.isAnnotationPresent(MultiTest.class)) {   //办法是否带有注解                System.out.println(m.getName()); //带注解名称的办法名                MultiTest multiTest = m.getAnnotation(MultiTest.class); //获取注解实例                try {                    m.invoke(null, multiTest.a(), multiTest.b());       //带括号                    passed++;                } catch (Throwable ex) {                    System.out.printf("Test %s failed: %s %n",m,ex.getCause());                    failed++;                }            }        }        System.out.printf("Passed: %d, Failed %d%n", passed, failed);     }}
  • 注解自身没有意义,只有通过某种配套的工具才会对注解信息进行拜访和解决
  • 主要用途:提供给编译器/IDE的工具