Is it possible just using Java?
The simple answer is decisive: "You do not want to do this!".
This is technically possible, but without resorting to extremely complex, expensive and fragile tricks, such as modifying bytecode 1 . And even then, you must rely on dynamic loading to access the modified type and (possibly) reflection in order to use its new members. In short, you will create a lot of pain for yourself, for a little, if you want.
Java is a statically typed language, and adding / modifying class type signatures can terminate the contract for static typing.
1 - AspectJ and the like allow you to introduce additional behavior into the class, but it is probably not the "runtime injection" you are using. Of course, the methods introduced will not be available for statically compiled code to be called.
source share