ClassLoader学习记录2
写程序的时候,时常会思考,我们的类是哪来的?为何我们想用sdk中的类,就有这个类呢?答案肯定是classloader读进虚拟机来的。那他究竟是怎么被加载到虚拟机中的呢?看看如何定制classloader的代码,就相当一目了然了。
main() { runClass(name, key);}public void runClass(String name, int key){ ClassLoader classLoader = new CryptoClassLoader(key); Class<?> c = classLoader.loadClass(); Method m = c.getMethod("main", String[].class); m.invoke(null, (Object)new String[]{});}class CryptoClassLoader extends ClassLoader{ int key; CryptoClassLoader(int key){ this.key = key } protected Class<?> findClass(String name) throws ClassNotFoundException{ byte[] classBytes = null; try{ classBytes = loadClassBytes(name); } catch(IOException e) { throw new ClassNotFoundException(); } Class<?> cl = defineClass(name, classBytes, 0, classBytes.length); if (cl == null) throw new ClassNotFoundException(name); return cl; } private byte[] loadClassBytes(String name) throws IOException{ String cname = name.replace(".","/") + ".caesar"; //(我怎么觉得应该是.class? 不太懂这里...不会印刷错误吧?) FileInputStream in = null; in = new FileInputStream(cname); try{ ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int ch; while((ch = in.read()) != -1){ byte b = (byte)(ch - key); buffer.write(b); } return b.toByteArray(); } finally { in.close(); } }}