如何在 Java 中注释代码块 [英] How to annotate a code block in Java
问题描述
是否可以对代码块进行注释?例如.用于循环还是简单的大括号?如果是这样,如何?
Is it possible to annotate a block of code? E.g. for cycle or simply curly brackets? If so, how?
First.java
package An;
import An.ForCycle;
class First {
public static void main(String[] args) {
First f = new First();
}
public First () {
@ForCycle
{ // error: illegal start of type {
int k;
}
@ForCycle
for (int i = 0; i < 5; i++) { // similar error (illegal start...)
System.out.println(i);
}
}
}
ForCycle.java
package An;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.SOURCE)
public @interface ForCycle {}
根据 http://www.javacodegeeks.com/2012/11/java-annotations-tutorial-with-custom-annotation.html
@Target – 指示注释类型适用的程序元素的种类.一些可能的值是类型、方法、构造函数、字段等.如果目标元注释不存在,则可以在任何程序元素上使用注释.
@Target – indicates the kinds of program element to which an annotation type is applicable. Some possible values are TYPE, METHOD, CONSTRUCTOR, FIELD etc. If Target meta-annotation is not present, then annotation can be used on any program element.
任何程序元素(我猜)也意味着阻塞,不是吗?那么为什么我不能注释 block 或 for 呢?我错过了什么?
Any program element (I guess) means also block, doesn't it? So why I can't annotate block or for? What am I missing?
感谢帮助
推荐答案
它的意思是任何程序元素已经列出的元素".
It means "any program element out of those already listed".
对于这件事的最后一句话,只需参考Java 语言规范:
For the final word on the matter, one simply refers to the Java Language Specification:
注解可以在任何声明中用作修饰符,无论是包、类(包括枚举)、接口(包括注解类型)、字段、方法、形式参数、构造函数还是局部变量.
Annotations may be used as modifiers in any declaration, whether package, class (including enums), interface (including annotation types), field, method, formal parameter, constructor, or local variable.
注解也可用于枚举常量.
Annotations may also be used on enum constants.
这篇关于如何在 Java 中注释代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!