获取java中通用接口的注释值

时间:2016-03-29 00:21:18

标签: java generics annotations

我正在尝试获取注释值。我的情况如下:

这是我宣布的注释。

@Retention(RetentionPolicy.RUNTIME)
 public @interface PluginMessage {
 String name();
 String version();
}

这是使用某些值的注释的类

@PluginMessage(name = "RandomName", version = "1")
public class Response{
 private Date Time;
}

这是一个通用界面,将在下一个代码段中使用。

public interface ResponseListener<E> {
  void onReceive(E response);
}

我通过调用以下代码来调用它:

  addListener(new ResponseListener<Response>() {
      @Override
      public void onReceive(Response response) {
        System.out.println();
      }
  });

这是addListener方法的实现:

public <E> void addListener(ResponseListener<E> responseListener) {
    Annotation[] annotations = responseListener.getClass().getAnnotations();

}

注释总是空的,对我做错了什么的想法?我想在这里得到它们的价值。

1 个答案:

答案 0 :(得分:1)

您可以在此处获得注释:

.addListener(new ResponseListener<Response>() {
        public void onReceive(Response response) {
            final Annotation[] annotations = response.getClass().getAnnotations();
            for (Annotation annotation : annotations) {
                System.out.println("annotation.toString() = " + annotation.toString());
            }
        }
    });

您的.addListener实施毫无意义。您必须将侦听器添加到侦听器池,而不是从ResponseListener(没有注释)实例获取注释。然后,当您收到响应时,您必须为每个侦听器调用listener.onReceive(...)。我相信应该在那里实施类似的东西。