レベルエンター山本大のブログ

面白いプログラミング教育を若い人たちに

BLOCKVROCKリファレンス目次はこちら

[翻訳]Guice User's Guide ■14. Creating Binding Annotations

バインディング用のアノテーションを作る

Where did this @Blue annotation just mentioned come from? You can create such an annotation easily, although the standard incantation you have to use is unfortunately a little complex:

先ほど話題に出たこの@Blueアノテーションは、どこから来たものなのでしょうか?実はそのようなアノテーションを簡単に作る事が出来ます。使用しなければならない基本的な決まり文句は残念ながら少し複雑ですが、容易にそのような注釈を作成することができます:

/**
 * Indicates we want the blue version of a binding.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface Blue {}

Luckily, we don't really have to understand it all just to use it. But for the curious, here's what all this boilerplate means:

運よく、使うだけなら全部を本当に理解する必要はありません。しかし、好奇心を満たすために、この配管コードの意味を以下に紹介しましょう。

  • @Rentention(RUNTIME) allows your annotation to be visible at runtime.
  • @Target({FIELD, PARAMETER}) is a courtesy to your users; it prevents @Blue from being applied to methods, types, local variables, and other annotations, where it would serve no purpose.
  • @BindingAnnotation is a Guice-specific signal that you wish your annotation to be used in this way. Guice will produce an error whenever user applies more than one binding annotation to the same injectable element.

  • @Rentention(RUNTIME)は、アノテーションが実行時に可視状態になることを許可します
  • @Target({FIELD, PARAMETER})は、ユーザーへの好意です; それはメソッド、タイプ、ローカル変数、および他のアノテーションに適用されることから、@Blueを防ぎます。それらの場所では、目的を全く果たさないでしょう。
  • @BindingAnnotationは、Guice独自の表示で、アノテーションはこの方法で利用するべきであるということを表しています。Guiceは、ユーザーが同じインジェクタブルな(注入可能な)要素に1つ以上の要素をバインディングするアノテーションを適用するときは、常にGuiceはエラーを発生させます。