我正在尝试获取注释值。这是我的场景如下:
这是我声明的注释。
@Retention(RetentionPolicy.RUNTIME)
public @interface PluginMessage {
String name();
String version();
}
这是对某些值使用注释的类
@PluginMessage(name = "RandomName", version = "1")
public class Response{
private Date Time;
}
这是一个通用接口(interface),将在下一个代码片段中使用。
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();
}
注释总是空的,知道我做错了什么吗?我试图在这里了解它们的值(value)。
最佳答案
您可以在这里获得注释:
.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(...)
。我相信类似的事情应该在那里实现。
关于java - java中获取泛型接口(interface)的注解值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36273394/