自己定义Classloader,能够获得了Class对象,但是强制转换为相应的对象是却总出现ClassCastException异常,不知道是怎么回事,强制转换为Object对象没有问题.

解决方案 »

  1.   

    只要是个类就可以转换成Object,因为它是所有类的父类。楼主好好看看你的类,和你的强制转换类,是否附和继承多态或接口多态。
      

  2.   

    没错的!我用其他方式都试过了,一定请注意我是自定义的ClassLoader.既扩展的java.lang.ClassLoader.负责加载类,这是最重要的!
      

  3.   

    MyInterface my = null;//MyInterface是接口.MyTest继承这个接口.
      ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
      Object obj = (Object)classLoader.loadClass("factor.MyTest").newInstance();
      my = (MyInterface)obj;
      上面的可以.
      MyClassLoader geCL = new GEClassLoader();
      

  4.   

    MyInterface  my  =  null;//MyInterface是接口.MyTest继承这个接口.  
    ClassLoader  classLoader  =  Thread.currentThread().getContextClassLoader();  
    Object  obj  =  (Object)classLoader.loadClass(  "factor.MyTest  ").newInstance();  my  =  (MyInterface)obj;  
       上面的可以.  
    MyClassLoader  myCL  =  new  MyClassLoader();  
    clazz = geCL.loadClass("factor.MyTest");
    Object obj = (Object)clazz.newInstance();
    my = (MyInterface)obj;
    最后一句抛出ClassCastException异常.
    请高手指教!
      

  5.   

    问题应该出在MyClassLoader  myCL  =  new  MyClassLoader();  
    你的MyClassLoader是如何覆盖实现findClass这个父类方法的
      

  6.   

    楼上说得一点没错,我开始实覆盖了loadClass方法总是出现这个问题,现在我改为覆盖findClass方法,问题解决了.我估计问题出在类的加载问题上,谢谢.