views:

43

answers:

2

How can I do this:

class Foo {
  public static Foo get() throws Exception {
    ClassLoader cl = new URLClassLoader(new URL[]{"foo.jar"}, null); // Foo.class is in foo.jar
    return (Foo)cl.loadClass("Foo").newInstance(); // fails on class cast
  }
}

What I need is for the JVM to consider the Foo instance from cl as if it is an instance of Foo from the classloader of the executing code.

I have seen these approaches, none of them good for me (the above example is a toy example):

  1. Load the class (or a separate interface) by a class loader that is a parent of both the calling code and created classloader
  2. Serialize and deserialize the object.
+1  A: 

Not possible. Class identity consists of the fully qualified name and the class loader.

Casting an object to a class with the same name loaded by different classloaders is no different than trying to cast a String to Integer.

Michael Borgwardt
A: 

Perhaps something using interfaces and java.lang.reflect.Proxy would suit your preferences. Using an InvocationHandler that finds and invokes the relevant method on the target class. (Note, any mobile-code security you have will be shot through if you do this.)

Tom Hawtin - tackline