dimanche 9 octobre 2016

How to dynamically and recursively decorate a class in Java/Scala?

Say I'm modeling dreams:

public interface Dream {

  void start();
}

public class SimpleDream implements Dream {
 // implementation here...
}

public class Inception implements Dream {

  Dream inner;

 // implementation here...
}

Now say I have a decorator class for these dreams:

public class Decorator implements Dream {

  Dream decorated;

  public void start() {

    // do something else
    decorated.start();
  }
}

I want to be able to write a method that'll take any Dream instance and decorate it with Decorator recursively (fields as well). I was able to write such a method with reflection, but I encountered a problem when trying to decorate a field of a sub-type of Dream:

public class LucidDream implements Dream {

  SimpleDream inner;

 // implementation here...
}

My generic method will try to set a new Decorator wrapping the SimpleDream into the inner field of LucidDream, and doing so (with Field.set) will throw an exception (java.lang.IllegalArgumentException: Can not set final X field Y to Z).

I tried using proxies but it didn't work.

P.S.
I'm actually using Scala, so (a) forgive me for my Java code, and (b) if this is somehow achievable only with Scala, I'd like to know that as well.





Aucun commentaire:

Enregistrer un commentaire