Skip to content

Instantly share code, notes, and snippets.

@morris821028
Last active February 26, 2018 23:33
Show Gist options
  • Save morris821028/fcb54bff49e8e6e9d62355c2c3dc77f9 to your computer and use it in GitHub Desktop.
Save morris821028/fcb54bff49e8e6e9d62355c2c3dc77f9 to your computer and use it in GitHub Desktop.
AspectJ Example
package cc;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Loggable {
String value() default "";
}
package cc;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
@Aspect
class CpExecLogger {
protected static int mStackIndex = 0;
@Before("execution(* *.*(..)) && @annotation(cc.Loggable)")
public void enter(JoinPoint pjp) throws Throwable {
mStackIndex++;
if (mStackIndex != 1)
return ;
StringBuilder cmd = new StringBuilder();
cmd.append(String.format("%s.%s(", pjp.getSignature().getDeclaringTypeName(), pjp.getSignature().getName()));
Object[] objs = pjp.getArgs();
for (int i = 0; i < objs.length; i++) {
if (i > 0)
cmd.append(", ");
if (objs[i] instanceof String)
cmd.append(String.format("\"%s\"", objs[i]));
else
cmd.append(objs[i]);
}
cmd.append(String.format(");"));
System.err.printf("[Log] %s\n", cmd);
}
@After("execution(* *.*(..)) && @annotation(cc.Loggable)")
public void exit(JoinPoint pjp) throws Throwable {
mStackIndex--;
}
}
public class Main {
@Loggable
static public<T> T slave(T f) {
System.out.println("[Slave] ... " + f);
return f;
}
@Loggable
static public<T> T butler(T a, T b) {
System.out.println("[Butler] Lord, " + a + b);
slave(a);
slave(b);
return a;
}
static public Integer hello() {
System.out.printf("Hello\n");
return 10;
}
public static void main(String[] args) {
Integer t = slave(30);
Integer h = butler(10, 20);
String str = butler("a", "bstr");
}
}
[Log] cc.Main.slave(30);
[Slave] ... 30
[Log] cc.Main.butler(10, 20);
[Butler] Lord, 1020
[Slave] ... 10
[Slave] ... 20
[Log] cc.Main.butler("a", "bstr");
[Butler] Lord, abstr
[Slave] ... a
[Slave] ... bstr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment