黑马程序员技术交流社区

标题: 关于Java注解的官方文档 [打印本页]

作者: Morgan    时间: 2015-6-23 11:36
标题: 关于Java注解的官方文档

  1. public @interface RequestForEnhancement {
  2.     int    id();
  3.     String synopsis();
  4.     String engineer() default "[unassigned]";
  5.     String date()    default "[unimplemented]";
  6. }
复制代码


  1. @RequestForEnhancement(
  2.     id       = 2868724,
  3.     synopsis = "Enable time-travel",
  4.     engineer = "Mr. Peabody",
  5.     date     = "4/1/3007"
  6. )
  7. public static void travelThroughTime(Date destination) { ... }
复制代码


  1. public @interface Preliminary { }
复制代码

  1. @Preliminary public class TimeTravel { ... }
复制代码


  1. public @interface Copyright {
  2.     String value();
  3. }
复制代码

  1. @Copyright("2002 Yoyodyne Propulsion Systems")
  2. public class OscillationOverthruster { ... }
复制代码

  1. import java.lang.annotation.*;
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Target(ElementType.METHOD)
  4. public @interface Test { }
复制代码

  1. public class Foo {
  2.     @Test public static void m1() { }
  3.     public static void m2() { }
  4.     @Test public static void m3() {
  5.         throw new RuntimeException("Boom");
  6.     }
  7.     public static void m4() { }
  8.     @Test public static void m5() { }
  9.     public static void m6() { }
  10.     @Test public static void m7() {
  11.         throw new RuntimeException("Crash");
  12.     }
  13.     public static void m8() { }
  14. }
复制代码

  1. import java.lang.reflect.*;

  2. public class RunTests {
  3.    public static void main(String[] args) throws Exception {
  4.       int passed = 0, failed = 0;
  5.       for (Method m : Class.forName(args[0]).getMethods()) {
  6.          if (m.isAnnotationPresent(Test.class)) {
  7.             try {
  8.                m.invoke(null);
  9.                passed++;
  10.             } catch (Throwable ex) {
  11.                System.out.printf("Test %s failed: %s %n", m, ex.getCause());
  12.                failed++;
  13.             }
  14.          }
  15.       }
  16.       System.out.printf("Passed: %d, Failed %d%n", passed, failed);
  17.    }
  18. }
复制代码

  1. $ java RunTests Foo
  2. Test public static void Foo.m3() failed: java.lang.RuntimeException: Boom
  3. Test public static void Foo.m7() failed: java.lang.RuntimeException: Crash
  4. Passed: 2, Failed 2
复制代码


作者: guohaichang    时间: 2015-6-23 11:40
顶!!!!
作者: 王冲6060    时间: 2015-6-23 19:28
感谢分享




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2