Women in Technology

Hear us Roar



Article:
  Inside Class Loaders
Subject:   Casting classes loaded from different effective classloaders
Date:   2003-11-17 10:56:57
From:   sasho
In normal circumstances the ClassCastException thrown when casting classes with the same type but with different effective classloaders is the desired behavior but in some cases we may need the cast to succeed. Just like in the examples in the article, we may need to invoke a method on a class loaded with a classloader different from the effective classloader of the instance we pass as an argument (in this case the class names will match but the classloaders will not). One possible workaround, if the class is serializable, is to serialize the instance and then deserialize it within a class loaded by the second classloader (thus creating an instance that has the correct type and the correct effective classloader) and pass the new instance as the argument. Although this works just fine, it's not really a very elegant answer to that problem and maybe you could suggest a better solution?
Main Topics Oldest First

Showing messages 1 through 2 of 2.

  • Casting classes loaded from different effective classloaders
    2003-11-19 04:39:16  anonymous2 [View]

    I know that these doesn't always help you, but there are as I see it, two possible solutions.

    One, where you use rmi to communicate, and let the class be downloaded via the stub's codebase. Here the interface must be on the clientside, and not the implementation.

    The other one is to use JMX, where use use, "tunneling" via the jmx framwork.

  • Casting classes loaded from different effective classloaders
    2003-11-18 12:40:57  schaefera [View]

    Hi

    As we will see in the next installment this is how J2EE invocation on remote interfaces go around the problem even when you call them within the server. However, the client that receives the class will actually load the class locally (with its own class loader) and then incorporate the values from the object stream. But that requires that the client has a compatible class defintion available and if not deserialization will fail. In the case you have a compatible version the class behind the newly created instance is NOT (if the client uses a different class loader) compatible to the original class because the two class types have different class loaders. Thus to send the data back you need to serialize/deserialze the class again.
    In the next part of this article series I will explain a little bit more in detail how J2EE deals with multiple class loaders and talk about serilization/deserialization.
    Nevertheless I do not have a more elegant solution to propose even thought I would like to have a possiblity in Java to force a upcast as long as the class types are compatible to avoid wasting a lot of time.

    -Andy