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

ClassLoader找错,这是网易一道笔试题
TypeA.class位于classpath下, /absolute_path/TypeA.class为其在文件系统中的绝对路径, 且类文件小于1k, MyClassLoader为一个自定义的类加载器, 下面的这段类加载程序是否正确, 如果有错请指出哪一行有错, 简述理由
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class Tester{
public static void main(String[] args){
?? MyClassLoader cl1=new MyClassLoader();
?? try{
??? File f=new File("/absolute_path/TypeA.class");
??? byte[] b=new byte[1024];
??? InputStream is=new FileInputStream(f);
??? int I=is.read(b);
??? Class c=cl1.defineMyClass(null,b,0,1);
??? TypeA a=(TypeA)c.newInstance();
?? }catch(Exception e){
??? e.printStacktrace();
?? }
}
}
------解决方案--------------------
InputStream is=new FileInputStream(f);
    int I=is.read(b);
    Class c=cl1.defineMyClass(null,b,0,1);

第三行有错,应该是 Class c = cl1.defineMyClass(null, b,0,l); 注意 l和1的区别
如果你没复制错的话 应该就是这个了
------解决方案--------------------
引用:
感觉这两行
int I=is.read(b);
Class c=cl1.defineMyClass(null,b,0,1);
都有问题。

改成如下
int readIndex = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
while((readIndex = is.read(b))!=-1){
baos.write(b, 0, readIndex);
}
b = baos.toByteArray();
Class c=cl1.defineMyClass(null,b,0,b.length);


差不多也可以这么处理,不过题目是说哪里有错,声明该class不超过1024字节大小,一次read应该能读全
------解决方案--------------------
引用:
TypeA a=(TypeA)c.newInstance();

类还没载入呢,你就用上了。。。



同意这位的,还有个问题:TypeA 不是 MyClassLoader加载的TypeA,不是有继承关系的classloader加载的类,赋值肯定会报错。
------解决方案--------------------
Hei,楼主

e.printStacktrace() 这行代码有错。
应该是
e.printStackTrace();
------解决方案--------------------
引用:
Quote: 引用:

Class c=cl1.defineMyClass(null,b,0,1);
     TypeA a=(TypeA)c.newInstance();

因为这段代码就不规范,强制类型转换没有考虑向下转型,很容易出现这种问题
需要instanceof 先判断一下吧 

问题我找到了,不过不是因为这问题,是因为不同classLoader加载的类不能互相赋值,否则会报ClassCastException

3Q