0

I am trying to add behavior to the setters of a variable within a class. To keep things simple let's say that I want to print something to the console whenever a variable is set. Moreover, I want to achieve this using reflection from within a trait that is mixed in the class.

Consider the following code:

class Foo(var bar: String) extends Logger {}

trait Logger { self =>
  // create mirrors to reflect on the delegate
  private val runtimeMr  = runtimeMirror(self.getClass.getClassLoader)
  private val instanceMr = runtimeMr.reflect(self)

}

How can I now:

1) get the setter method(s) from the instanceMr and, more importantly

2) add behavior to the execution of the setter (in my case printing bar before setting it)

Maarten
  • 207
  • 2
  • 13
  • 1
    Possible duplicate of [Scala: replace method at runtime](https://stackoverflow.com/questions/32040709/scala-replace-method-at-runtime) – Dmytro Mitin Jun 04 '19 at 14:50
  • [How to change method behaviour through reflection?](https://stackoverflow.com/questions/15966726/how-to-change-method-behaviour-through-reflection) – Dmytro Mitin Jun 04 '19 at 14:51

0 Answers0