开发者

In Scala, other than inheritance is there a technique to know when a base class method has been called?

开发者 https://www.devze.com 2023-03-31 04:44 出处:网络
For example, suppose I have the following base class for which I cannot modify the source code class Base {

For example, suppose I have the following base class for which I cannot modify the source code

class Base {
    def someMethod = ...
}

If I define a sub class

class Sub extends Base {
    override def someMethod = ...
}

开发者_运维知识库when I do

val sub = new Sub

Then I automatically "know" when someMethod has been called because sub.someMethod is triggered. However I would like to avoid subclassing so I was wondering if there was some technique whereby I could do

class NotSubclass {
    val Base = new Base
}

or similar

And somehow "attach" someMethod from Base so that NotSubclass would "know" when someMethod was called. To clarify someMethod is called externally I never make the call in my own code.


If you are modifying the behaviour of a class for which you don't have the source code, then you could try looking into Aspect-Oriented programming.

Aspects allow you to 'wrap' a method call so that you can log information, or modify the input parameters or return values, or even just replace the method call altogether.

If all you want to do is log information, then this would be a good way to go. However, Aspects can lead to code which is very hard to understand and follow if you use them everywhere, so be sure that it fits your use case.

You will need to define a pointcut for the method you are interested in.

The Scala-IDE uses aspects to weave code into the JDT, it uses AspectJ, so it does work with Scala.


If the method belongs to an interface you can reimplement that and wrap Base. Otherwise you are out of luck.


You mean like this?

class NotSubclass {
    val base = new Base

    def someMethod = base someMethod
}


I guess you could do it using byte code manipulation. PowerMock allows to mock constructors, so I'd guess the same technique could be used to replace the byte code of Base with something that does whatever you need to get done.

This approach of course will:

  • be extremely confusing for anybody being not aware of it.
  • fail if you don't have the classloaders under your control.
  • might break legal constraints
  • is just generally a bad idea for production code.
0

精彩评论

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

关注公众号