zinking zinking - 1 year ago 76
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) {
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
to me. The dynamic class loader will always reference
class loader as parent class loader , thus the
interface is always valid, the dynamic class loader always load a new
class which is compatible with the

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

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
is needed?

Answer Source

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

The original code does this (simplified):

Postman p = getPostman();
while(true) {

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) {

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