Advertisement
JeffGrigg

AnnotationsAndMarkerInterfaces

Jul 23rd, 2018
529
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.92 KB | None | 0 0
  1. import java.lang.annotation.Annotation;
  2. import java.lang.annotation.Retention;
  3. import java.lang.annotation.RetentionPolicy;
  4. import java.util.Arrays;
  5.  
  6. public class AnnotationsAndMarkerInterfaces {
  7.     public static void main(String[] args) {
  8.  
  9.         // Should we run this test?
  10.         final Annotation theSlowTestAnnotation = ((Class) TestClass.class).getAnnotation(SlowTestAnnotation.class);
  11.         if (theSlowTestAnnotation != null) {
  12.             System.out.println(TestClass.class.getName() + " has the @SlowTestAnnotation.  I don't want to run its tests.");
  13.         }
  14.  
  15.         // Is there another reason not to run the tests?
  16.         if (Arrays.stream(TestClass.class.getInterfaces()).anyMatch(interfaceClass -> interfaceClass == SlowTestMarkerInterface.class)) {
  17.             System.out.println(TestClass.class.getName() + " implements SlowTestMarkerInterface.  I don't want to run its tests.");
  18.         }
  19.  
  20.         // If I gave you an instance of the test...
  21.         final TestClass testClass = new TestClass();
  22.  
  23.         // Would you run the tests?
  24.         if (testClass instanceof SlowTestMarkerInterface) {
  25.             System.out.println(testClass + " implements SlowTestMarkerInterface.  I don't want to run its test!");
  26.         }
  27.  
  28.         // Heck; run the test anyway:
  29.         testClass.run();
  30.     }
  31. }
  32.  
  33. @Retention(RetentionPolicy.RUNTIME)
  34. @interface SlowTestAnnotation {
  35. }
  36.  
  37. interface SlowTestMarkerInterface {
  38. }
  39.  
  40. interface Test {
  41.     void run();
  42. }
  43.  
  44. @SlowTestAnnotation
  45. class TestClass implements Test, SlowTestMarkerInterface {
  46.     @Override
  47.     public void run() {
  48.         System.out.println("This test takes a long time to run!");
  49.         try {
  50.             Thread.sleep(5000);
  51.         } catch (final InterruptedException ex) {
  52.             // (This is one of those rare cases where it's OK to throw away the exception.)
  53.         }
  54.         System.out.println("OK; I finished running this test.");
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement