我无法解析aop中的类成员类型。
我的代码将是这样,
注释类:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Calculator{
Class processor();
String operation();
}
接口:
public interface CalculatorProcessor {
public List<String> doSomthing(ApplicationContext appContext, JoinPoint joinPoint);
}
Class:
public class CalculatorProcessorImpl implements CalculatorProcessor {
@Override
public List<String> doSomthing(ApplicationContext appContext, JoinPoint joinPoint) {
//joinpoint logices and get the return list
//for example consider list contains {"plus",""minus}
List<String> resultList = new ArrayList<>();
resultList.add("plus");
resultList.add("minus")l
return resultList;
}
}
注释声明:
@Calculator(operation="performSomething",processor= CalculatorProcessorImpl.class)
public Response perform(){
return .........;
}
方面类:
@Inject
ApplicationContext context;
@After(value = "@annotation(com.sample.v1.Calculator)")
public void perform(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Calculator cal = joinPoint.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes()).getAnnotation(Calculator.class);
//trying to parse the class get the result
CalculatorProcessor calProcessor = (CalculatorProcessor ) cal.processor().cast(CalculatorProcessor.class);
List<String> result = calProcessor.doSomthing(context,joinPoint);
System.out.println(result.get(0)); //plus
}
这里考虑我的接口,注释类和方面将在单独的jar中。通过添加此jar的依赖关系,我可以注释执行操作的方法
我尝试了不同的方法,但是无法调用该类。.建议一些获得此结果的方法。在此先感谢
正如我说的,我不知道您想使用人为设计的解决方案做什么,您应该先对其进行解释。然后,我们可以以有意义的方式回答您的问题。从整体上讲,不考虑您的方法问题的技术回答是:
Class
对象与相应类的实例之间存在很大差异。您不能只将前者转换为后者,并期望能够在不实例化该类的情况下对其调用实例方法。
通过反射方法从方法中提取注释的方法也非常难看,完全没有必要。只需将注释绑定到通知方法参数即可。
怎么样?
@After("@annotation(calculator)")
public void perform(JoinPoint joinPoint, Calculator calculator) throws Throwable {
CalculatorProcessor calProcessor = (CalculatorProcessor)
calculator
.processor()
.getDeclaredConstructor()
.newInstance();
List<String> result = calProcessor.doSomething(context, joinPoint);
System.out.println(result.get(0));
}