Search code examples
javaannotationsblock

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 {}

According to http://www.javacodegeeks.com/2012/11/java-annotations-tutorial-with-custom-annotation.html

@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?

Thanks for help


Solution

  • It means "any program element out of those already listed".

    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.