2016-12-14 13 views
0

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; 
    } 
} 
+0

あなたがそれを行うことができれば、何が役に立つでしょうか? – Sam

+0

@Sam注釈に基づいてコードを挿入できる[プロジェクトロンボク](https://projectlombok.org/)のようなものです。 – flakes

答えて

1

見るJLS §9.6.4.1 @Target

Annotation types may be applicable in declaration contexts, where annotations apply to declarations, or in type contexts, where annotations apply to types used in declarations and expressions.

456は整数リテラルではなく、宣言又はタイプあるので、注釈を付けることができません。

+0

意味があります。私はあなたがそれを使用する前にローカルとして表現を宣言しなければならないだろうと思う望ましい機能を得るために。 '@Foo int k = 456; int i = 123 + k; ' – flakes

+0

実際には、' int i =(@Foo int)123;も使えない理由を含めるように答えを更新できますか? '@Target(ElementType.TYPE_USE)@interface Foo {}'このようなアノテーションを宣言した場合、 'error:アノテーション型はこの種の宣言には適用できません。 ' – flakes

+1

' int i =(@Foo int)123; – Andreas