日期:2014-05-20  浏览次数:20778 次

问个关于class loader的问题
package com.dotest;

import java.net.URL;
import java.net.URLClassLoader;

public class Test {

private URLClassLoader loader;

public void doTest() {
resetLoader();
try {
Class testClass = Class.forName("com.dotest.test.ScopeTest", true,
loader);
TestIntf test = (TestIntf) testClass.newInstance();
test.doTest();
System.out.println("finished");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void resetLoader() {
loader = null;
try {
System.out.println("url: "
+ this.getClass().getResource("/testA.jar"));
loader = new URLClassLoader(new URL[] { this.getClass()
.getResource("/testA.jar") });
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String[] args) {
Test test = new Test();
test.doTest();
}
}


package com.dotest;
public interface TestIntf {
public void doTest();
}


以下代码在单独的jar里面
package com.dotest.test;

import com.dotest.TestIntf;

public class ScopeTest implements TestIntf {
@Override
public void doTest() {
System.out.println("doTest 111");
}
}


运行结果:
url: file:/C:/Users/linh/workspace/DynamicClassLoaderTest/bin/testA.jar
Exception in thread "main" java.lang.ClassCastException: com.dotest.test.ScopeTest cannot be cast to com.dotest.TestIntf
at com.dotest.Test.doTest(Test.java:15)
at com.dotest.Test.main(Test.java:51)

------解决方案--------------------
我只看懂了类型转换错误
------解决方案--------------------
我想你的本意是调用实现类ScopeTest的doTest方法吧,为什么还要
TestIntf test = (Te[/b]stIntf) testClass.newInstance();

我想你代码的本意应该是这样的吧??把强制转换去掉吧

 Class testClass = Class.forName("com.dotest.test.ScopeTest", true,
                    loader);
            TestIntf test = testClass.newInstance();
            test.doTest();
------解决方案--------------------
借口了实现类我就不写了,给你测试类中的代码,我测试没有问题,可以输出你想要的结果:

public class Test {

private URLClassLoader loader;

public void doTest() {
try {
Class testClass = Class.forName("com.ScopeTest");
TestIntf test = (TestIntf) testClass.newInstance();
test.doTest();
} catch (Exception e) {
e.printStackTrace();
}
}

public void resetLoader() {
loader = null;
try {
System.out.println("url: "
+ this.getClass().getResource("/testA.jar"));
loader = new URLClassLoader(new URL[] { this.getClass().getResource("/testA.jar") });
} catch (Exception e) {
e.printStackTrace();
}
}

/**
 * @param args
 */
public static void main(String[] args) {
Test tt = new Test();
tt.doTest();
}

}