Can a Java class add a method to itself at runtime?

It’s not simple. Once a class is loaded by a classloader, there is no way to change the methods of loaded classes. When a class is requested, a classloader will load it and link it. And there is no way (with Java) to change the linked code or to add/remove methods.

The only trick that comes to my mind is playing with classloaders. If we delete a custom classloader, then the classes loaded by that classloader should be deleted or inaccessible too. The idea that comes to my mind is to

  1. implement one custom classloader
  2. load the dynamic class with that custom classloader
  3. if we have an updated version of this class,
  4. remove the custom classloader and
  5. load the new version of this class with a new instance of the custom classloader

I leave that as food for thought, can’t prove, if this leads to a solution or if we have pitfalls.

As a simple answer to the question: No, we can’t change a loaded class like we can change the content of fields with reflection. (we can’t add or remove fields too).

Leave a Comment