I have a class A with a
public String toString() {
}
method.
It gets compiled. Also, I have several implementations of that method as a method body. This implementation uses A's fields.
I want to be able to dynamically substitute the contents of the toString() method with such or such an implementation. The point here is that I need A's fields in the implementation.
I must say, I cannot create subclasses of A. I must use this class only.
As I can guess, each implementation must be compiled before the first usage. But how would one do that?
The simplest solution would probably be to use a flag variable and analyze it before invoking such or such a method or even put everything into toString and use switch. But what if A doesn't know anything about its implementation itself? Can they be decoupled - the A class and its toString implementations?