Is there a way to swap myself (this) with some other object in Java?
In Smalltalk we could write
Object subclass:myClass [
"in my method I swap myself with someone else"
swapWith:anObject [
self become:anObject.
^nil
]
]
myClass subclass:subClass [
]
obj := myClass new.
obj swapWith:subClass new.
obj inspect.
Result is An instance of subClass
, obviously.
I need to do following in Java:
So, in short, how can I achieve in Java self become: (someClass new:someParameters)
? Are there some known design patterns I could use?
In its most general form, arbitrary object swapping is impossible to reconcile with static typing. The two objects might have different interfaces, so this could compromise type safety. If you impose constraints on how objects can be swapped, such a feature can be made type safe. Such feature never became mainstream, but have been investigated in research. Look for instead at Gilgul.
Closely related is reclassification, the ability to change the class of an object dynamically. This is possible in Smalltalk with some primitives. Again, this puts type safety at risks, never became mainstream, but has been investigated in research. Look at Wide Classes, Fickle, or Plaid.
A poor man's solution to object swapping is a proxy that you interpose between the client and the object to swap, or the use of the state and strategy design patterns.