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.