@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编程
@SuppressWarnings安全
@SuppressWarnings("deprecation") public void test(){ TestDemo demo = new TestDemo(); demo.test1(); demo.test2(); }
@SafeVarargsapp
@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框架
@FunctionalInterface public interface Runnable { public abstract void run(); }Runnable 就是一个典型的函数式接口,上面源码能够看到它就被 @FunctionalInterface 注解。
有:@Retention、@Documented、@Target、@Inherited、@Repeatable 5 种。ide
@Retentionsvg
Retention 的英文意为保留期的意思。当 @Retention 应用到一个注解上的时候,它解释说明了这个注解的的存活时间。函数式编程
取值以下:函数
@Documented单元测试
@Target
Target 是目标的意思,@Target 指定了注解运用的地方。
取值以下:
@Inherited
@Repeatable
注解的定义
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(); } }