本帖最后由 周恺 于 2012-7-18 08:12 编辑
高手帮忙看看,我的类加载器写好了以后,测试时会出现错误提示:
Exception in thread "main" java.lang.NoClassDefFoundError: ClassForTest (wrong name: d15Klo/com/cn/ClassForTest)
以下是代码
类加载器定义:
class MyClassLoader extends ClassLoader
{
private String path;
public void setPath(String path)
{
this.path = path;
}
private String loaderName;
MyClassLoader(String loaderName)
{
super();
this.loaderName=loaderName;
}
MyClassLoader(ClassLoader parent,String loaderName)
{
super(parent);
this.loaderName=loaderName;
}
public byte[] classByteArray(String name)//将class文件字节读入字节数组中.
{
//String className=name;
String className=name.replace('.', '\\');
FileInputStream fis=null;
ByteArrayOutputStream baos=null;
try
{
fis=new FileInputStream(new File(path+className+".class"));
baos=new ByteArrayOutputStream();
int buf=-1;
while((buf=fis.read())!=-1)
{
baos.write(buf);
}
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] classDate=baos.toByteArray();
return classDate;
// return null;
}
@Override
protected Class<?> findClass(String className)//重写findClass方法.
{
byte[] classData=classByteArray(className);
return defineClass(className,classData, 0, classData.length);//如果我这里使用张老师视频上过期的方法defineClass(classData, 0, classData.length);就会出现:
// java.lang.IllegalAccessException: Class d15Klo.com.cn.ClassLoadTest can not access a member of class d15Klo.com.cn.ClassForTest with modifiers ""这种错误.
}
}
类加载器测试:
public class ClassLoadTest
{
public static void main(String[] args) //throws ClassNotFoundException,
//InstantiationException, IllegalAccessException
{
MyClassLoader myClassLoader=new MyClassLoader("myClassLoader").newInstance();
myClassLoader.setPath("F:\\");
try
{
myClassLoader.loadClass("ClassForTest");
} catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
想了2小时了,请各位帮帮忙.
|
|