7

注釈があります:

@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({METHOD, TYPE})
public @interface Example {
}

そして、その処理のためのインターセプター クラス:

@Interceptor
@Example
public class ExampleInterceptor implements Serializable {
...
}

パラメータテキストを追加したい:

public @interface Example {
    String text();
}

しかし、インターセプタークラスでパラメーターを処理する方法がわかりません。クラスの注釈を変更するには?

@Interceptor
@Example(text=???????)
public class ExampleInterceptor implements Serializable {
...
}

と書く@Example(text="my text")と、メソッド/クラスに で注釈が付けられたときにインターセプターが呼び出され@Example(text="my text")ます。しかし、インターセプターがパラメーター値で独立して呼び出されるようにしたい - @Example(text="other text").

パラメータ値を取得する方法は?リフレクションを使用する必要がありますか、それともより良い方法がありますか?

4

2 に答える 2

16

@Nonbindingアノテーションが使用されると、すべての属性値に対してインターセプターが呼び出されます。

注釈:

public @interface Example {
    @Nonbinding String text() default "";
}

インターセプター:

@Interceptor
@Example
public class ExampleInterceptor implements Serializable {
    ...
}
于 2012-05-15T10:51:29.830 に答える
0

まず、パラメータが 1 つしかない場合は、名前を付けvalueてパラメータ名をスキップできます (デフォルト)。=> は、次のように text= の部分をスキップできます。

@Example("my text") //instead of @Example(test="My text")
public class ...

注釈にアクセスするには、最初に取得する必要がある、、または型のメソッドgetAnnotationを使用します。次に、メソッドを呼び出すことができるアノテーションのインスタンスを取得します。ClassMethodFieldConstructor

Example example = getClass().getAnnotation(); //if you are inside the interceptor you can just use getClass(), but you have to get the class from somewhere
example.value(); //or example.text() if you want your annotation parameter to be named text.
于 2012-05-05T22:21:38.453 に答える