如何在java中从引用调用方法并发送到注释
我有一个接口I和一个抽象类a,我有我的自定义注释MyAnnotation,它应该将参数作为a的子类S,现在在处理注释时,我想调用具体类S的方法 哪一个有效如何在java中从引用调用方法并发送到注释,java,java-8,annotations,Java,Java 8,Annotations,我有一个接口I和一个抽象类a,我有我的自定义注释MyAnnotation,它应该将参数作为a的子类S,现在在处理注释时,我想调用具体类S的方法 哪一个有效 //In spring aspect before processing I am getting method annotation and trying to call m1() annotation.ref().m1() //Error annotation.ref2().m1() //Error 你不能就这样做。首先需要类的实例
//In spring aspect before processing I am getting method annotation and trying to call m1()
annotation.ref().m1() //Error
annotation.ref2().m1() //Error
你不能就这样做。首先需要类的实例。 如果您的A类是Spring的bean,那么可以注入ApplicationContext并从中获取bean。然后可以调用一个方法
@Autowired
private ApplicationContext context;
void test(MyAnnotation annotation) {
A bean = context.getBean(annotation.ref());
bean.m1();
}
不能在批注中使用新XX。注释参数可以使用一组非常特定的类型:
原始的
一串
班
枚举
另一个注释
上面任意一个的数组
看
因此,要完成您试图完成的任务,您必须使用一个类
然后必须使用反射来创建实例并调用该方法
Class<?> clazz = annotation.ref();
I instance = (I) cls.getConstructor().newInstance();
instance.m1();
看
所有类都必须没有参数构造函数,否则,您只能以这种方式实例化某些对象,而不能以其他方式导致您必须基于类有条件地进行分支。Abstract和public的扩展A不正确。我认为I cls.newInstance.m1比…getMethod…invoke…更好。@ernest_k newInstance从9开始就不推荐使用;最好调用构造函数::newInstance@Eugene这是正确的。我的评论只是关于避免getMethod…调用。。。部分,如果你注意到…@ernest_k+Eugene,你们都是对的。这是一个有点懒惰的回答,大部分只是从我列出的源代码中复制和粘贴。我现在已经改进了
@Autowired
private ApplicationContext context;
void test(MyAnnotation annotation) {
A bean = context.getBean(annotation.ref());
bean.m1();
}
Class<?> clazz = annotation.ref();
I instance = (I) cls.getConstructor().newInstance();
instance.m1();