Tuesday, 17 March 2009

Information from the AOP JoinPoint

I know. Logging is the most overdone and boring application of AOP, but even if you are planning on doing something more interesting with it, logging information about the method that triggered the advice is useful.

Here's just a couple of very simple reference examples on getting information about the joinpoint in the advice. They might save you five minutes hunting around in the JavaDocs. Let's start with Spring AOP/AspectJ:

public static final String getJoinPointDetails(JoinPoint joinPoint) {
    String className = joinPoint.getSignature().getDeclaringType().getName();
    String methodName = joinPoint.getSignature().getName();
    String paramList = CollectionUtil.listToString(joinPoint.getArgs());
    return className + " " + methodName + "(" + paramList + ")";

And the equivalent in an EJB3 interceptor:

public static final String getJoinPointDetails(InvocationContext invocationContext) {
    String className = invocationContext.getTarget().getClass().getName();
    String methodName = invocationContext.getMethod().getName();
    String paramList = CollectionUtil.listToString(invocationContext.getParameters());
    return className + " " + methodName + "(" + paramList + ")";

In both cases getName() is from java.lang.Class and returns the package name as a prefix to the class name. If you prefer a shorter version, you can use getSimpleName() to omit the package name.

The CollectionUtil.listToString() would go something like this:

public static final String listToString(List list) {
    StringBuilder sb = new StringBuilder();
    if (list != null) {
        for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            String s = o == null ? "<null>" : o.toString();
            sb.append(i == 0 ? s : ", " + s);
    return sb.toString();

public static final String listToString(Object[] array) {
    return listToString(Arrays.asList(array));

All very simple but handy things to tuck away in a library somewhere.

No comments: