表达式的注释

时间:2016-12-14 20:31:52

标签: java annotations

在Java中,您可以向局部变量添加注释,但是,是否可以在表达式上添加注释? (我假设答案是否定的,但我认为无论如何都会问)我最好猜测它的外观,但它没有编译。

@interface Foo {}

class Bar {
    void bar() {
        // local variable annotation
        @Foo int i = 123 + 456;
        // expression annotation
        // error: illegal start of expression
        int j = 123 + @Foo 456;
        // error: annotation type not applicable to this kind of declaration
        int j = 123 + (@Foo int) 456;
    }
}

1 个答案:

答案 0 :(得分:1)

请参阅JLS §9.6.4.1 @Target

  

注释类型可能适用于声明上下文,其中注释适用于声明,或类型上下文,其中注释适用于声明和表达式中使用的类型。

456是整数文字,而不是声明类型,因此无法进行注释。