score:5

Accepted answer

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.

score:0

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.

score:1

you mean like this?

class notsubclass {
    val base = new base

    def somemethod = base somemethod
}

score:2

if the method belongs to an interface you can reimplement that and wrap base. otherwise you are out of luck.


Related Query

More Query from same tag