我可以在方法体内使用注释吗?

时间:2013-06-05 20:26:07

标签: java exception annotations

允许Java注释的语义将它们放在在函数体内的某个位置,例如,注释特定的函数调用,语句或表达式?

例如:

class MyClass {
    void theFunc(Thing thing) {
        String s = null;
        @Catching(NullPointerException)   //<< annotation ?
          s = thing.getProp().getSub().getElem().getItem();
        if(s==null)
            System.out.println("null, you fool");
    }
}

缩写经常写的(太常见,绝对!):

class MyClass {
    void theFunc(Thing thing) {
        String s = null;
        try {
            s = thing.getProp().getSub().getElem().getItem();
        } catch(NullPointerException ex) { }
        if(s==null) 
            System.out.println("null, you fool");            
    }
}

如果嵌入式注释的概念可行吗?或类似的东西?

1 个答案:

答案 0 :(得分:7)

ElementType指定注释的有效目标。你不能注释任何旧陈述。它基本上缩小到宣言;声明:

  • 注释类型
  • 构造
  • 字段
  • 本地变量
  • 方法
  • 参数