Java:如何编写自己的Java类加载器
1个回答
2018-06-21 · 国内最优秀java资源共享平台
关注
展开全部
给你简单介绍一下类加载器
1.类加载器就加载字节码文件(.class)
public class FileClassLoader extends ClassLoader { String rootDir=null; public FileClassLoader(String rootDir) { this.rootDir = rootDir; } @Override protected Class<?> findClass(String className) throws ClassNotFoundException { //首先检查是否已经被加载了。 Class<?> c = findLoadedClass(className); String path = rootDir + "/" + className.replace('.', '/') + ".class"; if (c != null) { return c; } else { /*双亲委托模式*/ ClassLoader loaderParent = this.getParent(); c = loaderParent.loadClass(className); if (c != null) { return c; } else { /*如果再不行的话,就再进行加载。因为字节码的本质就是一个字节数组*/ InputStream is = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { is = new FileInputStream(path); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } c = defineClass(className, buffer, 0, buffer.length); } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } return c; } }}
/*
相同的类加载器对同一个类进行加载,得到的hascode是相同的
* 不同的类加载器对同一类进行加载,得到的hascode是不一样的*/public class Demo { public static void main(String[] args) { FileClassLoader loader = new FileClassLoader("c://myjava"); FileClassLoader loader2=new FileClassLoader("c://myjava"); try { Class<?> c = loader.findClass("com.lg.test.HelloWorld"); Class<?> c0=loader.findClass("com.lg.test.HelloWorld"); Class<?> c1=loader2.findClass("com.lg.test.HelloWorld"); Class<?> c2=loader.findClass("com.lg.test.Demo01"); Class<?> c3=loader.findClass("java.lang.String"); System.out.println(c.hashCode()); System.out.println(c.getClassLoader()); System.out.println(c0.hashCode()); System.out.println(c0.getClassLoader()); System.out.println(c1.hashCode()); System.out.println(c1.getClassLoader()); System.out.println(c2.hashCode()); System.out.println(c2.getClassLoader()); System.out.println(c3.hashCode()); System.out.println(c3.getClassLoader()); } catch (ClassNotFoundException e) { e.printStackTrace(); } }}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询