これが私のユースケースです:
メソッドのパラメーターに基づいて、特定のクラスの各メソッドの前後に一般的な操作を行う必要があります。例えば:
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;
}