zinking zinking - 3 months ago 15
Java Question

can dynamically load classes be rebind to static reference?

Reference: dynamic load java code

public interface Postman {
void deliverMessage(String msg);
}

//loaded by dynamic class loader, with parent class loader pointing to main
public class PostmanImpl implements Postman {
}

public class PostmanApp {
public static void main(String[] args) throws Exception {
Postman postman = getPostman();
while (true) {
//postman.deliverMessage(msg);
getPostman().deliverMessage(msg);
}
}
private static Postman getPostman() {
// Omit for now, will come back later
// ???
}
}



How do you access the up-to-date dynamic class with a static reference? Apparently, a direct (normal) reference to a dynamic class's object will not do the trick.


I don't quite follow the above statement. not
apparent
to me. The dynamic class loader will always reference
main
class loader as parent class loader , thus the
Postman
interface is always valid, the dynamic class loader always load a new
Impl
class which is compatible with the
interface
.

InvocationHandler handler = new DynaCodeInvocationHandler(...);
Postman proxy = (Postman) Proxy.newProxyInstance(
Postman.class.getClassLoader(),
new Class[] { Postman.class },
handler);


The author eventually suggested using a Proxy to delegate calls on interface to newly loaded implementation.


Apparently, a direct (normal) reference to a dynamic class's object will not do the trick.


what's the problem with direct reference assignment of newly loaded class? why eventually a
Proxy
is needed?

Answer

You've already fixed the code so that it's not necessary.

The original code does this (simplified):

Postman p = getPostman();
while(true) {
    p.deliverMessage();
}

There's no way for the code in Postman to change the object p refers to. When it loads the updated class and creates a new instance of the new class, p still refers to the old instance of the old class.

But if you do this instead:

while(true) {
    getPostman().deliverMessage();
}

then getPostman will return an instance of the new class once it's loaded, and there is no problem.