Is the a way to add a new functionality to a non extend-able class i.e(final class ) in Java , I know a way to add a property to it using HashMap .for example if i have a Widget class that declared final and i want to add a new property to it lets say ‘serial code’ then i can you the HashMap to add it like this
serialHashMap.put(widgetObject,serialNumber);
so is there a way to add new functionality to a final class , any suggestions ??? thanks
That doesn’t add anything to the object in question; it assumes a reasonable hashCode/equals, and associates the data with the object.
You could use the same methodology and something resembling a command pattern to associate an interface implementation with the object.
Your best bet might be to composite the object into your own class, though. Only your code will be able to utilize the new functionality, so it might as well be encapsulated.
(I’m ignoring things like adding interfaces through byte-code manipulation, proxies, and so on.)