注解说明与使用方法

预置注解

@Deprecatedweb

  • 这个元素是用来标记过期的元素,编译器在编译阶段遇到这个注解时会发出提醒警告,告诉开发者正在调用一个过期的元素好比过期的方法、过期的类、过期的成员变量。
    public class TestDemo{
        @Deprecated
        public void test1(){
            System.out.println("test1...");
        }
        public void test2(){
            System.out.println("test2...");
        }
    }
    定义了一个 Hero 类,它有两个方法 test1() 和 test2() ,其中 test2() 被 @Deprecated 注解。能够看到,test2() 方法上面被一条直线划了一条,这其实就是编译器识别后的提醒效果。

@Override编程

  • 提示子类要复写父类中被 @Override 修饰的方法

@SuppressWarnings安全

  • 阻止警告的意思。以前说过调用被 @Deprecated 注解的方法后,编译器会警告提醒,而有时候开发者会忽略这种警告,他们能够在调用的地方经过 @SuppressWarnings 达到目的。
    @SuppressWarnings("deprecation")
    public void test(){
        TestDemo demo = new TestDemo();
        demo.test1();
        demo.test2();
    }

@SafeVarargsapp

  • 参数安全类型注解。它的目的是提醒开发者不要用参数作一些不安全的操做,它的存在会阻止编译器产生 unchecked 这样的警告。它是在 Java 1.7 的版本中加入的。
    @SafeVarargs // Not actually safe!
        static void m(List<String>... stringLists) {
        Object[] array = stringLists;
        List<Integer> tmpList = Arrays.asList(42);
        array[0] = tmpList; // Semantically invalid, but compiles without warnings
        String s = stringLists[0].get(0); // Oh no, ClassCastException at runtime!
    }
    上面的代码中,编译阶段不会报错,可是运行时会抛出 ClassCastException 这个异常,因此它虽然告诉开发者要妥善处理,可是开发者本身仍是搞砸了。Java 官方文档说,将来的版本会受权编译器对这种不安全的操做产生错误警告。

@FunctionalInterface框架

  • 函数式接口注解,这个是 Java 1.8 版本引入的新特性。函数式编程很火,因此 Java 8 也及时添加了这个特性。函数式接口 (Functional Interface) 就是一个具备一个方法的普通接口,能够很容易转换为 Lambda 表达式。
    @FunctionalInterface
    public interface Runnable {
        public abstract void run();
    }
    Runnable 就是一个典型的函数式接口,上面源码能够看到它就被 @FunctionalInterface 注解。

自定义注解

元标签

有:@Retention、@Documented、@Target、@Inherited、@Repeatable 5 种。ide

@Retentionsvg

  • Retention 的英文意为保留期的意思。当 @Retention 应用到一个注解上的时候,它解释说明了这个注解的的存活时间。函数式编程

  • 取值以下:函数

    • RetentionPolicy.SOURCE 注解只在源码阶段保留,在编译器进行编译时它将被丢弃忽视。
    • RetentionPolicy.CLASS 注解只被保留到编译进行的时候,它并不会被加载到 JVM 中。
    • RetentionPolicy.RUNTIME 注解能够保留到程序运行的时候,它会被加载进入到 JVM 中,因此在程序运行时能够获取到它们。

@Documented单元测试

  • 顾名思义,这个元注解确定是和文档有关。它的做用是可以将注解中的元素包含到 Javadoc 中去。

@Target

  • Target 是目标的意思,@Target 指定了注解运用的地方。

  • 取值以下:

    • ElementType.ANNOTATION_TYPE 能够给一个注解进行注解
    • ElementType.CONSTRUCTOR 能够给构造方法进行注解
    • ElementType.FIELD 能够给属性进行注解
    • ElementType.LOCAL_VARIABLE 能够给局部变量进行注解
    • ElementType.METHOD 能够给方法进行注解
    • ElementType.PACKAGE 能够给一个包进行注解
    • ElementType.PARAMETER 能够给一个方法内的参数进行注解
    • ElementType.TYPE 能够给一个类型进行注解,好比类、接口、枚举

@Inherited

  • Inherited 是继承的意思,可是它并非说注解自己能够继承,而是说若是一个超类被 @Inherited 注解,若是该超类还有其余非元注解的注解,那么其子类就继承了超类的非元注解的注解。

@Repeatable

  • Repeatable 是可重复的意思。@Repeatable 是 Java 1.8 才加进来的特性。

注解的定义与属性

注解的定义

  • 注解经过 @interface 关键字进行定义。
    public @interface TestAnnotation {
    }

注解的属性

  • 注解的属性也叫作成员变量。注解只有成员变量,没有方法

  • 注解的成员变量在注解的定义中以“无形参的方法”形式来声明,其方法名定义了该成员变量的名字,其返回值定义了该成员变量的类型。

  • 示例

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface TestAnnotation {
        int id();
        String msg();
    }
    
    @TestAnnotation(id=3,msg="hello annotation")
    public class Test {
    }
  • 示例:给属性默认值

    • 下面反射将使用该注解进行测试
    @Target(ElementType.TYPE,ElementType.FILED,Type.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface TestAnnotation {
        public int id() default -1;
        public String msg() default "Hi";
    }
    
    @TestAnnotation()
    public class Test {}
  • 示例:注解内仅仅只有一个名字为 value 的属性时

    public @interface TestAnnotation{
        String value();
    }
    
    @TestAnnotation("test")
    public class Test {}
    
    //和下面效果是同样
    @TestAnnotation(value="test")
    public class Test {}
  • 示例:注解没有任何属性

    public @interface TestAnnotation{
    }
    
    @TestAnnotation
    public class Test {}

注解与反射

经过反射首先要获取class对象。

  • 判断是否应用了某个注解

    public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {}
  • 若是存在 获取 Annotation 对象

    public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {}
  • 获取所有注解

    public Annotation[] getAnnotations() {}
  • 示例:获取类上的注解

    @TestAnnotation
    public class Test {
        public static void main(String[] args) {
            boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class);
            if ( hasAnnotation ) {
                TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class);
                System.out.println("id:"+testAnnotation.id());
                System.out.println("msg:"+testAnnotation.msg());
            }
        }
    }
  • 示例:获取方法或者属性上的注解

    public class Test {
        @TestAnnotation
        public void testMethod(){}
    
        @SuppressWarnings("deprecation")
        public void test1(){
        }
    
        public static void main(String[] args) throws Exception  {
             Method testMethod = Test.class.getDeclaredMethod("testMethod");
             if ( testMethod != null ) {
    			// 获取方法中的注解
    			Annotation[] ans = testMethod.getAnnotations();
    			for( int i = 0;i < ans.length;i++) {
    				System.out.println("method testMethod annotation:"+ans[i].annotationType().getSimpleName());
    			}
    		}
    	}
    }
  • 示例:获取字段上注解

    public class Test {
        @TestAnnotation
        int a;
    
        public static void main(String[] args) throws Exception {
           Field a = Test.class.getDeclaredField("a");
    		a.setAccessible(true);
    		//获取一个成员变量上的注解
    		TestAnnotation testAnnotation = a.getAnnotation(TestAnnotation .class);
    		if ( check != testAnnotation ) {
    			System.out.println("testAnnotation value:"+testAnnotation .value());
    		}
        }
    }

使用自定义注解

  • 开发者使用了Annotation 修饰了类、方法、Field 等成员以后,这些 Annotation 不会本身生效,必须由开发者提供相应的代码来提取并处理 Annotation 信息。这些处理提取和处理 Annotation 的代码统称为 APT(Annotation Processing Tool)。

  • 注解的使用历来都是结合反射

  • 示例:自定义单元测试框架

    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyTest {
    }
    public class TestDemo{
        @MyTest
        public void suanShu(){
            System.out.println("1234567890");
        }
        @MyTest
        public void jiafa(){
            System.out.println("1+1="+1+1);
        }
        @MyTest
        public void jiefa(){
            System.out.println("1-1="+(1-1));
        }
        @MyTest
        public void chengfa(){
            System.out.println("3 x 5="+ 3*5);
        }
        @MyTest
        public void chufa(){
            System.out.println("6 / 0="+ 6 / 0);
        }
    }
    public class TestTool {
        public static void main(String[] args) {
            TestDemo testobj = new TestDemo();
            Class clazz = testobj.getClass();
            Method[] method = clazz.getDeclaredMethods();
            
            //用来记录测试产生的 log 信息
            StringBuilder log = new StringBuilder();
            // 记录异常的次数
            int errornum = 0;
            
            for ( Method m: method ) {
                // 只有被 @MyTest标注过的方法才进行测试
                if ( m.isAnnotationPresent( MyTest.class )) {
                    try {
                        m.setAccessible(true);
                        m.invoke(testobj, null);
                    } catch (Exception e) {
                        errornum++;
                        log.append(m.getName()).append(" ").append("has error:").append("\n\r  caused by ")
    	                    //记录测试过程当中,发生的异常的名称
    	                    .append(e.getCause().getClass().getSimpleName()).append("\n\r")
     	                    //记录测试过程当中,发生的异常的具体信息
    						.append(e.getCause().getMessage()).append("\n\r");
                    } 
                }
            }
            log.append(clazz.getSimpleName()).append(" has  ").append(errornum).append(" error.");
            // 生成测试报告
            System.out.println(log.toString());
        }
    }
  • 示例:改进工厂模式

    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyFactory {
    	String value();
    }
    package net.yzx66.test.anno
    
    public interface Target{ }
    
    public class Target1 implements Target{ }
    public class Target2 implements Target{ }
    @MyFactory("net.yzx66.test.anno.Target1")
    public class TestDemo{
    
    	private Target target;
    	
        public TestDemo(){
        	 MyFactory myFactory=this.getClass().getAnnotation(MyFactory.class);
        	 String class=myFactory.getValue();
        	 Class<?> cls = Class.forName(class) ;	// 取得Class对象
    		 this.target=cls.newInstance();
       }
    }