El Guapo
El Guapo

Reputation: 5781

How to create an aspect around a method in a class that implements java.security.Principal?

Does anyone know how one would go about creating an aspect around the method "getName()" in a class that implements the interface java.security.Principal?

I am using spring and below is the pertinent parts of my Class:

@Aspect
public class MyPrincipalAspect {
    @PointCut("(execution(* java.security.Principal.getName(..)))")
    private void getNamePC(){}

    @Around("getNamePC()")
    public Object getNameJP(ProceedingJoinPoint pjp) throws Throwable {
        Object retVal = pjp.proceed();
        return retVal;
    }
}

I actually want to do something with "retVal", however, I'm just using the above as a trivial example. I have other Aspects within my application and they all work just fine.

I read something on the AspectJ site regarding not being able to load-time weave classes from the java package, but they say it's still possible (but, they don't give any examples).

I've also tried going through a non-Spring approach (using an aop.xml file with javaagent defined in my app-server config params).

Any help is much appreciated.

Thanks.

Upvotes: 1

Views: 1348

Answers (1)

kriegaex
kriegaex

Reputation: 67317

You have several options:

  • If you can control the client classes calling getName, you can use a call pointcut instead of execution. This way you do not need to weave any JDK classes.
  • If the Principal subclasses you want to intercept are not JDK, but third-party classes (you did not mention), you can weave them easily at compile or load time.
  • If you really need to weave JDK/JRE classes, use compile time weaving in the existing class files, creating new woven ones in your output directory. Then use those to replace the original JDK/JRE classes, copying them to the default location. That should be good enough for debugging and maybe even for productive use, as long as you have the runtime environment under your control.
  • Maybe (I do not know because I have not tried) there is a way to write a class loader which will load the runtime weaver classes first, but it does not sound likely or like a simple option. I would have to do a web search or some coding experiments by myself in order to find out.

Update: Oh by the way, in your pointcut you might want to use Principal+ instead of just Principal in order to also intercept overridden methods.

Upvotes: 1

Related Questions