如何在Java中注释代码块 [英] How to annotate a code block in Java

查看:1182
本文介绍了如何在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 - 表示注释类型适用的程序元素的种类。一些可能的值是TYPE,METHOD,CONSTRUCTOR,FIELD等。如果不存在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.

任何程序元素(我猜)也意味着阻止,不是吗?那么为什么我不能为阻止注释?我缺少什么?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆