这是我的用例:
我需要在给定类的每个方法之前和之后做一些通用操作,这基于方法的参数。例如:
void process(Processable object) {
LOGGER.log(object.getDesc());
object.process();
}
class BaseClass {
String method1(Object o){ //o may or may not be Processable(add process logic only in former case)
if(o intstanceof Prcessable){
LOGGER.log(object.getDesc());
object.process();
}
//method logic
}
}
我BaseClass
有很多方法,我知道将来也会将相同的功能添加到几个类似的类中。可能会出现以下情况吗?
@MarkForProcessing
String method1(@Process Object o){
//method logic
}
PS:可以使用AspectJ/guice吗?也想知道如何从头开始实现这一点以便理解。
编辑:忘了提,我尝试过的。(不完整或工作)
public @interface MarkForProcessing {
String getMetadata();
}
final public class Handler {
public boolean process(Object instance) throws Exception {
Class<?> clazz = instance.getClass();
for(Method m : clazz.getDeclaredMethods()) {
if(m.isAnnotationPresent(LocalSource.class)) {
LocalSource annotation = m.getAnnotation(MarkForProcessing.class);
Class<?> returnType = m.getReturnType();
Class<?>[] inputParamTypes = m.getParameterTypes();
Class<?> inputType = null;
// We are interested in just 1st param
if(inputParamTypes.length != 0) {
inputType = inputParamTypes[0];
}
// But all i have access to here is just the types, I need access to the method param.
}
return false;
}
return false;
}