命名模式的缺点有以下三点:(在第 4 版之前,JUnit 测试框架要求其用户通过以 test[Beck04] 开始名称来指定测试方法)

  1.拼写错误导致失败,但不会提示。

  2.无法确保它们仅用于适当的程序元素。

  3.它们没有提供将参数值与程序元素相关联的好的方法。

下面以Junit4为例来说明注解的优势

/**
* 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);
 }
}

从 Java 8 开始,还有另一种方法来执行多值注解。 可以使用 @Repeatable 元注解来标示注解的声明,而不用
使用数组参数声明注解类型,以指示注解可以重复应用于单个元素。

// 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() { ... }

 

总结:当可以使用注解代替时,没有理由使用命名模式。所有程序员都应该使用 Java 提供的预定义注解类型。

最新文章

  1. [APUE]进程控制(上)
  2. ASP.NET Core中显示自定义错误页面-增强版
  3. Swift开发第十二篇——protocol组合&amp;static和class
  4. Linux之我见
  5. 前端开发之Chrome插件
  6. String当中的高效函数(优化)
  7. 《C Primer Plus 第五版》读书笔记
  8. memcached在项目中的应用
  9. RS485通讯协议的应用 (转)
  10. 安装Django时报错&#39;module&#39; object has no attribute &#39;lru_cache&#39;
  11. Error: Default interface methods are only supported starting with Android N (--min-api 24): java.io.InputStream org.apache.poi.sl.usermodel.ObjectShape.readObjectData()
  12. ul li 实现层级列表显示
  13. go第三方日志系统-seelog-使用文档
  14. LOJ2250 [ZJOI2017] 仙人掌【树形DP】【DFS树】
  15. open-falcon实现邮件报警
  16. 思维导图-mysql log
  17. 5.2&amp;5.3
  18. .NET Core开发日志——Dapper与MySQL
  19. WebService注解总结
  20. 微信小程序 Unexpected end of JSON input/Unexpected token o in JSON at position 1

热门文章

  1. 使用hexo,创建博客
  2. 滑动表层div时 禁止底层滑动
  3. 使用 GitHub 开源项目申请 IntelliJ License
  4. jvm GC算法和种类
  5. IAR软件使用的快捷键配置以及配置cc2530环境
  6. springboot创建,自动装配原理分析,run方法启动
  7. MVC03
  8. 从web现状谈及前端性能优化
  9. Linux学习4-部署LAMP项目
  10. DOM是什么(初级版)