Search code examples
javaproxy-classesdynamic-proxyjavassist

Enhancing a java object at runtime


I am aware that using proxy capable libraries (javassist, JDK dynamic proxies, etc) that it is possible to enhance a class to implement an interface at runtime.

My question is: is it possible to enhance an instantiated object to implement an interface at runtime (and likewise provide appropriate method handlers).


Solution

  • No, we can't change a class that has already been loaded. And we can't replace a loaded class (within a classloader).

    There may be a chance if you

    • load a class with a custom classloader
    • unload the classloader (should unload the class aswell)
    • load the modified class again with a new classloader instance

    But that is very, very black magic...