如何在 Java 中获取接口或抽象类方法的注释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23994338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:36:42  来源:igfitidea点击:

How to get annotations of interface or abstract class methods in Java

java

提问by ibrahimyilmaz

I have an interface like this:

我有一个这样的界面:

public interface IFoo{
@AnnotationTest(param="test")
String invoke();
}

and I implement this like this:

我是这样实现的:

public class Foo implements IFoo{
@Override
public String invoke(){
  Method method = new Object() {
        }.getClass().getEnclosingMethod();
  AnnotationTest ann = method.getAnnotation(AnnotationTest.class);
  if(ann == null){
    System.out.printl("Parent method's annotation is unreachable...")
}

}

}

If it is possible to reach parent's annotation, I want to learn the way of it.

如果有可能达到父母的注释,我想学习它的方式。

Any help or idea will be appreciated.

任何帮助或想法将不胜感激。

回答by NimChimpsky

you can't inherit annotations.

你不能继承注解。

But a framework that uses an annotation can check to see if annotation is present on superclass

但是使用注解的框架可以检查超类上是否存在注解

回答by superbob

You can use Spring AnnotationUtils.findAnnotationto read annotations from interfaces.

您可以使用 Spring AnnotationUtils.findAnnotation从接口读取注释。

Example :

例子 :

Interface I.java

界面 I.java

public interface I {
    @SomeAnnotation
    void theMethod();
}

Implementing class A.java

实现类 A.java

public class A implements I {
    public void theMethod() {
        Method method = new Object() {}.getClass().getEnclosingMethod();
        SomeAnnotation ann = AnnotationUtils.findAnnotation(method, AnnotationTest.class);
    }
}

It obviously requires to include in your project (and import) Spring framework classes.

它显然需要在您的项目中包含(并导入)Spring 框架类。

回答by Serge Ballesta

There is no direct way to get it. If you really need, you have to manually loop over getInterfaces()to find if any implemented interface has the annotation. If you want to search for (eventually abstract) superclasses and the annotation is not @Inherited, you can again iterate the superclass chain until finding Object(*).

没有直接的方法可以得到它。如果您确实需要,则必须手动循环getInterfaces()以查找任何已实现的接口是否具有注释。如果您想搜索(最终是抽象的)超类而注释不是@Inherited,您可以再次迭代超类链,直到找到Object(*)。

But beware, as following post states, there are good reasons for this not to be directly implemented in Java : Why java classes do not inherit annotations from implemented interfaces?

但请注意,正如以下帖子所述,这有充分的理由不能在 Java 中直接实现:为什么 Java 类不从实现的接口继承注释?

(*) If the annotation is @Inheritedit is automatically searched on superclasses, but not on interfaces.

(*) 如果注解是@Inherited它会在超类上自动搜索,但不会在接口上搜索。