我有一个接口我和抽象类一,我有我的自定义注解MyAnnotation 应采取参数作为子类小号的一个,现在在处理注释我想打电话给具体类的方法小号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() //Errorannotation.ref2().m1() //Error
2 回答
白衣染霜花
TA贡献1796条经验 获得超10个赞
您不能new XX()
在注释中使用。注释参数可以使用一组非常具体的类型:
原始
细绳
班级
枚举
另一个注解
以上任何一个的数组
看到这个答案。
因此,要完成您想要完成的工作,您必须使用一个类。
然后,您必须使用反射来创建实例并调用该方法。
Class<?> clazz = annotation.ref();
I instance = (I) cls.getConstructor().newInstance();
instance.m1();
看到这个答案。
您的类必须都具有无参数构造函数,否则您只能以这种方式实例化某些类,而不能实例化其他类(导致您必须根据类有条件地进行分支)。
慕婉清6462132
TA贡献1804条经验 获得超2个赞
你不能就那样做。您首先需要一个类的实例。如果你的A类是一个Spring'sbean,你可以ApplicationContext从那里注入和获取 bean。然后你可以调用一个方法。
@Autowired
private ApplicationContext context;
void test(MyAnnotation annotation) {
A bean = context.getBean(annotation.ref());
bean.m1();
}
添加回答
举报
0/150
提交
取消