java JVM-自定义类加载器

自定义文件系统类加载器

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 Tt {

public static void main(String[] args) throws Exception {

    Loader loader=new Loader("d:myjva");
    Loader loader2=new Loader("d:myjva");
    Class<?> c=loader.loadClass("cn.sxt.in.HelloWorld");
    Class<?> c2=loader.loadClass("cn.sxt.in.HelloWorld");
    Class<?> c3=loader2.loadClass("cn.sxt.in.HelloWorld");
    Class<?> c4=loader2.loadClass("java.lang.String");
    Class<?> c5=loader2.loadClass("cn.sxt.in.helloworld"); //调用项目下的文件
    //加载器不一样加载相同类会被JVM认为是不同类
    System.out.println(c.hashCode());
    System.out.println(c2.hashCode());
    System.out.println(c3.hashCode());
    System.out.println(c4.hashCode());
    System.out.println(c3.getClassLoader());  //返回自定义的加载器
    System.out.println(c4.getClassLoader()); //用的引导类加载器,返回null
    System.out.println(c5.getClassLoader()); //返回的是应用类加载器
}
}

猜你喜欢

转载自blog.51cto.com/14437184/2439088