How to replace standard call to System.currentTimeMillis() via AspectJ?

34 Views Asked by At

I'm trying to replace System.currentTimeMillis() with own value. It's needed for test cases. Code example:

package org.example.aspectj;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class TimeAspect
{
    @Around("execution(public static native long currentTimeMillis())")
    public long changeCallsToCurrentTimeInMillisMethod(ProceedingJoinPoint pjp)
    {
        return 0;
    }
}
package org.example.aspectj;

public class TimeDemo
{
    public static void main(String[] args) {
        long currentTimeMillis = System.currentTimeMillis();
        System.out.println("currentTimeMillis -> " + currentTimeMillis);
    }
}
[warning] advice defined in org.example.aspectj.TimeAspect has not been applied [Xlint:adviceDidNotMatch]

A see answer:

Task :TimeDemo.main()
  currentTimeMillis -> 1710770641050

So the time is not changed. What is wrong?

1

There are 1 best solutions below

0
kriegaex On

You cannot weave aspects into JDK classes by conventional means, and I am not going to elaborate on advanced use cases for JDK weaving here.

The simple solution is to weave the aspect into your application code instead, because that is what you control during compilation. Simply use call instead of execution in order to weave into the calling code instead of the called code.

@Around("call(public static native long currentTimeMillis())")

Console log after the change:

currentTimeMillis -> 0