我可以在方法体中使用注释吗?
问题描述:
允许 Java 注释的语义将它们放在函数体内的某个位置,例如注释特定的函数调用、语句或表达式?
Allows the semantics of Java annotations to place them somewhere inside a functions body, e.g. to annotate a specific function call, statement or expression?
例如:
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");
}
}
缩写经常写的(太频繁了,绝对!):
To abbreviate the often written (too often, definitly!):
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");
}
}
这个嵌入式注释的概念是否可行?或者类似的东西?
If the concept of this embedded annotation possible at all? Or something similar?
答
ElementType 指定注释的有效目标.您不能注释任何旧语句.它基本上缩小到声明;声明:
ElementType specifies the valid targets of an annotation. You can't annotate any old statement. It's basically narrowed down to declarations; declarations of:
- 注释类型
- 构造函数
- 字段
- 局部变量
- 方法
- 包装
- 参数
- 输入