是否可以使用像 AspectJ 这样的 AOP 库来实现这一点?
当然可以。这是 AspectJ 中典型的初学者练习,如下所示:
public class SampleClass {
public SampleClass() { super(); }
public SampleClass(String s) { this(); }
public SampleClass(int i) { this(); }
public void method01(String s, Number n, Throwable t) {}
public void method02(int i, String s, double d) {}
public void method03(String s) {}
public void method04() {}
public void method05(String s, Number n, double d) {}
public static void main(String[] args) {
new SampleClass().method01("foo", new Integer(11), new RuntimeException("error"));
new SampleClass("test").method02(11, "bar", Math.PI);
new SampleClass(123).method03("zot");
new SampleClass("another test").method04();
new SampleClass(456).method05("baz", new Integer(11), Math.E);
}
}
现在您只需要编写一个切面来拦截所有方法执行(以及可选的构造函数执行,如下所示):
public aspect MethodArgsAspect {
pointcut allMethods() : execution(* *(..));
pointcut allConstructors() : execution(*.new(..));
before() : !within(MethodArgsAspect) && (allMethods() || allConstructors()) {
System.out.println(thisJoinPointStaticPart.getSignature());
for (Object arg : thisJoinPoint.getArgs())
System.out.println(" " + arg);
}
}
运行时SampleClass.main
,这方面将打印:
void SampleClass.main(String[])
[Ljava.lang.String;@7fdcde
SampleClass()
void SampleClass.method01(String, Number, Throwable)
foo
11
java.lang.RuntimeException: error
SampleClass()
SampleClass(String)
test
void SampleClass.method02(int, String, double)
11
bar
3.141592653589793
SampleClass()
SampleClass(int)
123
void SampleClass.method03(String)
zot
SampleClass()
SampleClass(String)
another test
void SampleClass.method04()
SampleClass()
SampleClass(int)
456
void SampleClass.method05(String, Number, double)
baz
11
2.718281828459045