开发者

Dynamic Proxy using Scalas new Dynamic Type

开发者 https://www.devze.com 2023-02-15 03:41 出处:网络
Is it possible to create an AOP like interceptor using Scalas new Dynamic Type feature? For example: Would it be possible开发者_如何学编程 to create a generic stopwatch interceptor thatcould be mixed

Is it possible to create an AOP like interceptor using Scalas new Dynamic Type feature? For example: Would it be possible开发者_如何学编程 to create a generic stopwatch interceptor that could be mixed in with arbitrary types to profile my code? Or would I still have to use AspectJ?


I'm pretty sure Dynamic is only used when the object you're selecting on doesn't already have what you're selecting:

From the nightly scaladoc:

Instances x of this trait allow calls x.meth(args) for arbitrary method names meth and argument lists args. If a call is not natively supported by x, it is rewritten to x.invokeDynamic("meth", args)

Note that since the documentation was written, the method has been renamed applyDynamic.


No.

In order for a dynamic object to be supplied as a parameter, it'll need to have the expected type - which means inheriting from the class you want to proxy, or from the appropriate superclass / interface.

As soon as you do this, it'll have the relevant methods statically provided, so applyDynamic would never be considered.


I think your odds are bad. Scala will call applyDynamic only if there is no static match on the method call:

class Slow {
  def doStuff = //slow stuff
}
var slow = new Slow with DynamicTimer
slow.doStuff

In the example above, scalac won't call applyDynamic because it statically resolved your call to doStuff. It will only fall through to applyDynamic if the method you are calling matches none of the names of methods on the type.

0

精彩评论

暂无评论...
验证码 换一张
取 消