本帖最后由 Simple_love 于 2013-10-27 22:56 编辑
先写个继承java.net.URLClassLoader的类,如下- package kite.jvm;
- import java.net.URL;
- import java.net.URLClassLoader;
- public class OneURLClassLoader extends URLClassLoader {
- // 类加载器的parent默认为系统AppClassLoader.
- public OneURLClassLoader(URL[] urls) {
- super(urls);
- }
- // 使用父类的findClass(String name)方法加载类.
- public Class findClass(String name) throws ClassNotFoundException {
- return super.findClass(name);
- }
- }
复制代码 接下来写个接口,如下:- package kite.jvm;
- public interface OneInterface {}
复制代码 紧接着写个实现上面接口的一个类,如下:- package kite.jvm;
- public class Constant implements OneInterface {}
复制代码 写个含main方法的类测试下,如下:- package kite.jvm;
- import java.net.URL;
- public class Run {
- public static void main(String[] args) throws Exception {
- // class字节码所在的位置.
- String dir = "file:/Development/workspace/jvm/bin/";
- URL url = new URL(dir);
- OneURLClassLoader oucl = new OneURLClassLoader(new URL[]{url});
- // 用类加载器加载kite.jvm.Constant并返回它的class对象.
- Class c = oucl.findClass("kite.jvm.Constant");
- // 根据class对象c实例化一个对象,用它的接口类型(OneInterface)做类型转换.
- OneInterface instance1 = (OneInterface) c.newInstance();
- // 根据class对象c实例化一个对象,用它的实际类型(Constant)做类型转换.
- //Constant instance2 = (Constant) c.newInstance();
- System.out.println(instance1);
- //System.out.println(instance2);
- }
- }
复制代码 如果打开注释掉的那两条代码,运行结果打印如下:
Exception in thread "main" java.lang.ClassCastException: kite.jvm.Constant cannot be cast to kite.jvm.Constant
at kite.jvm.Run.main(Run.java:12)
问题:解释下异常的出现,在此情景中接口和实际类型转化的区别
|