effective-java study notes --- notes better than naming pattern 39

Named disadvantages of the following three modes :( prior edition 4, JUnit testing framework requires its user to test [Beck04] Start the test method specified name)

  1. spelling mistakes lead to failure, but will not be prompted.

  2. ensure that they can not be used only for appropriate program elements.

  3. They do not provide a good method parameter value associated with a program element.

Below Junit4 example to illustrate the advantages of annotations

/**
* Indicates that the annotated method is a test method.
* Use only on parameterless static methods.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test {
}
// Program to process marker annotations
import java.lang.reflect.*;
public class RunTests {  public static void main(String[] args) throws Exception {   int tests = 0;   int passed = 0;   Class<?> testClass = Class.forName(args[0]);   for (Method m : testClass.getDeclaredMethods()) {     if (m.isAnnotationPresent(Test.class)) {       tests++;       try {         m.invoke(null);         passed++;       } catch (InvocationTargetException wrappedExc) {         Throwable exc = wrappedExc.getCause();         System.out.println(m + " failed: " + exc);       } catch (Exception exc) {         System.out.println("Invalid @Test: " + m);       }     }   }   System.out.printf("Passed: %d, Failed: %d%n",passed, tests - passed);  }
}

Starting Java 8, there is another way to perform multi-value notes. @Repeatable element may be used to designate annotation statement notes, without
using an array type parameters declared annotation, annotation can be applied repeatedly to indicate a single element.

 

// Repeatable annotation type
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Repeatable(ExceptionTestContainer.class)
public @interface ExceptionTest {
  Class<? extends Exception> value();
}
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
public @interface ExceptionTestContainer {   ExceptionTest[] value(); }

// Code containing a repeated annotation
@ExceptionTest(IndexOutOfBoundsException.class)
@ExceptionTest(NullPointerException.class)
public static void doublyBad() { ... }

 

Summary: When you can use annotations in place, there is no reason to use the naming pattern. All programmers should use the predefined annotation types Java provides.

 

Guess you like

Origin www.cnblogs.com/zsmcwp/p/11607030.html