Thomas Baer
Thomas Baer

Reputation: 39

How and can I dynamically create a subclass of an unknown class?

Here is my scenario. I have a plugin system. The plugins can detect and lookup each other at run time via a master list of plugins. The hierarchy is such

Base Class A
----Unknown Class B extends A
--------Known method from Class A, we'll call it E
--------Dynamically generated Class F extends B
------------Overridden Method E
------------Other methods inherited from A and B

F should inherit behavior from B, with the exception that E is overridden. F is then instantiated separately from B as a different object with similar but not identical behavior. The class B is not known at compile time, but it can be identified with an iteration and check for instance of A in the master list of plugins.

My specific case involves a game. Not necessarily what I'm doing, but a good example would be finding every sword added by other plugins, and then making a new copy of the sword, with all the same abilities, except it shoots fire instead of whatever fancy swing effect it may have had originally, and method E determines what happens when the sword is swung.

Upvotes: 0

Views: 186

Answers (1)

stevecross
stevecross

Reputation: 5684

You can use a bytecode engineering toolkit like javassist. It allows you to create new classes based on your existing class and lets you change the method body.

Upvotes: 2

Related Questions