cast across classloader?

Posted by IttayD on Stack Overflow See other posts from Stack Overflow or by IttayD
Published on 2010-04-07T10:57:49Z Indexed on 2010/04/07 11:03 UTC
Read the original article Hit count: 397

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about classloader