【问题标题】:How to call method from a reference send to annotation in javajava - 如何从引用发送到Java中的注释调用方法
【发布时间】:2019-03-12 10:56:42
【问题描述】:

我有一个接口 I 和一个抽象类 A ,我有我的自定义注释 MyAnnotation 应该将参数作为子类 A的S,现在在处理注释时我想调用具体类的方法S

public interface I{
   void m1();
}

public abstract class A implements I {
    public abstract void m1();
}

public @interface MyAnnotation {
    public Class< ? extends A> ref();
    public Class< ? super A> ref2();
}

public S extends A{
    public void m1() {}
}

我正在注释方法,例如

@MyAnnotation(ref= new XX() )  or @MyAnnotation(ref= XX.class )
@MyAnnotation(ref= new yy() ) or @MyAnnotation(ref= yy.class )

无论哪个有效

//In spring aspect before processing I am getting method annotation and trying to call m1()  
annotation.ref().m1() //Error
annotation.ref2().m1() //Error

【问题讨论】:

  • abstarctpublic S extends A 不正确

标签: java java-8 annotations


【解决方案1】:

您不能在注释中使用new XX()。注释参数可以使用一组非常具体的类型:

  • 原始
  • 字符串
  • 一个枚举
  • 另一个注解
  • 上述任何一项的数组

this answer

所以要完成你想要完成的事情,你必须使用一个类。

然后您必须使用反射来创建实例并调用该方法。

Class<?> clazz = annotation.ref();
I instance = (I) cls.getConstructor().newInstance();
instance.m1();

this answer

您的类都必须有无参数的构造函数,否则您只能以这种方式实例化一些,而不能实例化其他的(导致您必须根据类有条件地分支)。

【讨论】:

  • 我认为((I) cls.newInstance()).m1()...getMethod(...).invoke(...) 更好
  • @ernest_k newInstance 自 9 起已弃用;最好拨打Constructor::newInstance
  • @Eugene 没错。我的评论只是避免getMethod(...).invoke(...) 部分,如果您注意到...
  • @ernest_k + Eugene,你们都说得对。这是一个有点懒惰的答案,主要是从我列出的来源中复制和粘贴的。我现在改进了它
【解决方案2】:

你不能像那样简单地做到这一点。您首先需要一个类的实例。 如果您的 A 类是 Spring's bean,您可以注入 ApplicationContext 并从那里获取 bean。然后就可以调用方法了。

@Autowired
private ApplicationContext context;

void test(MyAnnotation annotation) {
    A bean = context.getBean(annotation.ref());
    bean.m1();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    相关资源
    最近更新 更多