Is there a way to substitute (override) an implementation of a Java class that is already loaded by the loader of the System class with another implementation (available as an array of bytes)?
To illustrate my doubts, this code follows:
public class Main { public static void main(String ... args) { Foo foo = new Foo(); foo.print(); ClassLoader cl = ... Foo foo2 = (Foo) cl.newInstance(); foo2.print(); } }
The print () method of the first Foo prints "Implementation 1", and the second prints "Implementation 2". The second instance of foo is retrieved by the class loader from the byte array (which can be stored in a file or retrieved from any stream ...)
PS: The requirement that Foo is a class, not an interface, and cannot be extended, that is, the actual bytes (inside the virtual machine) that define the implementation of the class, are overridden.
java classloader runtime
Carlos Eduardo Melo
source share