Artem Malinko Artem Malinko - 1 month ago 10
Scala Question

@AspectJ. Pointcut for scala (and probably java) lambdas

Is it possible to have poitcut for scala lambdas? If I'm not mistaken scala lambdas now compiled in the same way as java lambdas, so I think my question is also applicable for java lambdas, but I'm not sure.

Here is the code. Basically I want to advice Runnable instances. And it works perfectly if I use classes or anonymous class, but it doesn't work if I use lambdas.

@Around("execution(* (com.test..* && java.lang.Runnable+).run())")
def runnableAspect(pjp: ProceedingJoinPoint): Any = {
println("Runnable caught")
pjp.proceed()
}


And here is the test code:

package com.test

class Greet {

def hello(): Unit = {
println("-----start--------")
run(new Runnable {
override def run(): Unit = println("anonymous class")
})
println("------------------")
run(() => println("lambda"))
println("-----end--------")

}

private def run(r: Runnable) = r.run()

}


Output is:

-----start--------
Runnable caught
anonymous class
------------------
lambda
-----end--------


Is it possible at all? And if it is, what am I doing wrong?

Answer Source

Bases on this answer.

For Java

@Around("execution(void com.test..lambda*(..)) || execution(* (com.test..* && java.lang.Runnable+).run())")

For Scala

@Around("execution(void com.test..$anonfun*(..)) || execution(* (com.test..* && java.lang.Runnable+).run())")