编写接口
实现类
将AImpl打成JAR包,放置于c:/下
测试类
运行结果:
[color=red]true
false
false
Exception in thread "main" java.lang.ClassCastException: com.skyon.cl.test.AImpl cannot be cast to com.skyon.cl.test.A
at com.skyon.cl.test.ClassloaderTest.main(ClassloaderTest.java:37)[/color]
[color=blue][size=large]结果可证明接口引用与实现类处于不同ClassLoader不能兼容[/size]。[/color]
/*
* Copyright (c) 2008 Skyon Technology Ltd.
* All rights reserved.
*
* project: ims
* create: 2013-6-7
* cvs: $Id: $
*/
package com.skyon.cl.test;
/**
* TODO (2013-6-7 上午10:27:23) 请添加 A 类的注释。
* @author dylan0514
* @version $Revision: 1.1 $
*/
public interface A {
}
实现类
/*
* Copyright (c) 2008 Skyon Technology Ltd.
* All rights reserved.
*
* project: ims
* create: 2013-6-7
* cvs: $Id: $
*/
package com.skyon.cl.test;
/**
* TODO (2013-6-7 上午10:28:26) 请添加 AImpl 类的注释。
* @author dylan0514
* @version $Revision: 1.1 $
*/
public class AImpl implements A {
}
将AImpl打成JAR包,放置于c:/下
测试类
/*
* Copyright (c) 2008 Skyon Technology Ltd.
* All rights reserved.
*
* project: ims
* create: 2013-6-7
* cvs: $Id: $
*/
package com.skyon.cl.test;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
/**
* TODO (2013-6-7 上午10:27:06) 请添加 ClassloaderTest 类的注释。
* @author dylan0514
* @version $Revision: 1.1 $
*/
public class ClassloaderTest {
/**
* @param args
* @throws MalformedURLException
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static void main(String[] args) throws MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
// TODO (2013-6-7 上午10:27:06) 自动生成方法存根
URLClassLoader url = new URLClassLoader(new URL[]{new URL("file:///c:/test.jar")},null);
Class azz = (Class) url.loadClass("com.skyon.cl.test.AImpl");
System.out.println(A.class.isAssignableFrom(AImpl.class));
System.out.println(A.class.isAssignableFrom(azz));
System.out.println(azz == AImpl.class);
A a = (A) azz.newInstance();
System.out.println("azz:"+azz.getClassLoader()+" A:" + A.class.getClassLoader() +" AImpl:"+AImpl.class.getClassLoader());
}
}
运行结果:
[color=red]true
false
false
Exception in thread "main" java.lang.ClassCastException: com.skyon.cl.test.AImpl cannot be cast to com.skyon.cl.test.A
at com.skyon.cl.test.ClassloaderTest.main(ClassloaderTest.java:37)[/color]
[color=blue][size=large]结果可证明接口引用与实现类处于不同ClassLoader不能兼容[/size]。[/color]