开发者

Java type casting

I have three files:

ScriptProcessor.java:

public interface ScriptProcessor {
   public String someMethod();
}

ScriptProcessorDummy.java:

public class ScriptProcessorDummy implements ScriptProcessor {
   public String someMethod{
       return "some string";
   }
}

In the main method, the code does the following:

URLClassLoader loader = null;
loader = new URLClassLoader(new URL[] {new URL("JARFILE")});
if (loader != null) {
   ScriptProcessor processor = (ScriptProcessor) loader.loadClass("ScriptProcessorDummy").newInstance();
}

"JARFILE" contains class files of ScriptProcessor and ScriptProcessorDummy.

The code works fine when using JDK 1.4 but when using JDK 1.5, the typecast (to ScriptProcessor) fails 开发者_如何学Gowith java.lang.ClassCastException.

Could somebody please tell me how to fix this.

Thanks, Raj


You need to make your current class loader the parent of the new class loader you are loading, and make sure that there isn't a copy of the interface in your jar.

The problem you have suggests that you have two copies of the interface: one in the main class loader, one in your new one. The object returned uses the one in the separate jar, but your class is using the main one. They aren't the same. You have to make sure that Java uses the same '.class' for the interface when processing the loaded class as it did when it compiled your code.

The first thing to do is 'jar tf' on the jar and see if my hypothesis of two copies is correct. If so, remove it. Try running. If you now get a NoClassDef, fix the construction of the loader.

new URLClassLoader(urlArray, Thread.currentThread().getContextClassLoader());

assuming that your environment maintains the context class loader. Alternatively,

new URLClassLoader(urlArray, ScriptProcessor.class.getClassLoader());


Try using:

loader.loadClass("ScriptProcessorDummy", true).newInstance();

the boolean tell the classloader to resolve the class name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜