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?
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
callinstead ofexecutionin order to weave into the calling code instead of the called code.Console log after the change: