ClassLoader觅错,这是网易一道笔试题
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的区别
如果你没复制错的话 应该就是这个了
------解决方案--------------------
差不多也可以这么处理,不过题目是说哪里有错,声明该class不超过1024字节大小,一次read应该能读全
------解决方案--------------------
同意这位的,还有个问题:TypeA 不是 MyClassLoader加载的TypeA,不是有继承关系的classloader加载的类,赋值肯定会报错。
------解决方案--------------------
Hei,楼主
e.printStacktrace() 这行代码有错。
应该是
e.printStackTrace();
------解决方案--------------------
3Q
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的区别
如果你没复制错的话 应该就是这个了
------解决方案--------------------
差不多也可以这么处理,不过题目是说哪里有错,声明该class不超过1024字节大小,一次read应该能读全
------解决方案--------------------
同意这位的,还有个问题:TypeA 不是 MyClassLoader加载的TypeA,不是有继承关系的classloader加载的类,赋值肯定会报错。
------解决方案--------------------
Hei,楼主
e.printStacktrace() 这行代码有错。
应该是
e.printStackTrace();
------解决方案--------------------
3Q