自定义文件系统类加载器
public class Loader extends ClassLoader{
private String rootDir;
public Loader(String rootDir)
{
this.rootDir=rootDir;
}
//重写父类方法
protected Class<?> findClass(String name) throws ClassNotFoundException{
Class<?> c=findLoadedClass(name); //查找已经被加载的类,返回Class类的实例
//不为空则返回已经加载过的类
if(null!=c)
{
return c;
}else //如果没有类,让父类去加载
{
ClassLoader parent =this.getParent();
try {
c=parent.loadClass(name); //委派父类加载
}catch(Exception e)
{
e.printStackTrace();
}
if(c!=null)
{
return c;
}else //如果还没获取,则读取d:/myjava/cn/sxt/in/User.class下的文件,转换成字节数组
{
byte[] classData=getClassData(name);
if(classData==null)
{
throw new ClassNotFoundException(); //如果没加载到,手动抛出异常
}else
{
c=defineClass(name,classData,0,classData.length);
}
}
}
return c;
}
private byte[] getClassData(String classname)
{
String path=rootDir+"/"+classname.replace('.', '/')+".class";
ByteArrayOutputStream bos=null;
InputStream is=null;
try {
is=new FileInputStream(path);
bos=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len=-1;
while((len=is.read(buffer))!=-1)
{
bos.write(buffer,0,len);
}
bos.flush();
return bos.toByteArray();
}
catch(Exception e)
{
e.printStackTrace();
}finally {
try { if(null!=is)
{
is.close();
}
}catch(IOException e)
{
e.printStackTrace();
}
try
{
if(null!=bos)
{
bos.close();
}
}catch(IOException e)
{
e.printStackTrace();
}
}
return null;
}
}public class Loader extends ClassL