単一のパラメータで複数の注釈を取得する方法 - Javaの?

Skyyangレン:

私はこのようなメソッドを持っている場合:

   testLink(@LinkLength(min=0, max=5) List<@LinkRange(min=5, max=9) Integer> link) { ... }

どのように私は両方の@LinkLengthと@LinkRange注釈を得るのですか?

なスロー:

私はあなたが反射的これらの注釈にアクセスしたいと仮定しています。ここでは例を示します。

package com.example;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedParameterizedType;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.List;

public class Main {

  @Retention(RetentionPolicy.RUNTIME)
  @Target({ElementType.PARAMETER, ElementType.TYPE_USE})
  public @interface Foo {

    String value();
  }

  public static void bar(@Foo("parameter") List<@Foo("type_use") Integer> list) {}

  public static void main(String[] args) throws NoSuchMethodException {
    Method method = Main.class.getMethod("bar", List.class);

    // get annotation from parameter
    Parameter parameter = method.getParameters()[0];
    System.out.println("PARAMETER ANNOTATION = " + parameter.getAnnotation(Foo.class));

    // get annotation from type argument used in parameter
    AnnotatedParameterizedType annotatedType =
        (AnnotatedParameterizedType) parameter.getAnnotatedType();
    AnnotatedType typeArgument = annotatedType.getAnnotatedActualTypeArguments()[0];
    System.out.println("TYPE_USE ANNOTATION  = " + typeArgument.getAnnotation(Foo.class));
  }
}

これは以下のように出力します。

PARAMETER ANNOTATION = @com.example.Main$Foo(value="parameter")
TYPE_USE ANNOTATION  = @com.example.Main$Foo(value="type_use")

ここで使用される方法は、以下のとおりです。

上記の例は、約完璧な知識を利用しますbar方法を。言い換えれば、私は1つのパラメータがあることを知っていた、私は知っていたParameter#getAnnotatedType()戻ってくるAnnotatedParameterizedType、と私は、パラメータ型が1型引数を持っていたことを知っていました。反射的任意のクラスをスキャンするとき、この情報を使用して、適切なチェックを追加し、適切な場合にのみ、特定のアクションを実行する必要がありますつまり、先に-のタイム知られることはありません。例えば:

AnnotatedType type = parameter.getAnnotatedType();
if (type instanceof AnnotatedParameterizedType) {
  // do something...
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=19270&siteId=1
おすすめ