銀行轉帳案例(爲了方便,本身爲本身動態代理,沒有再寫類)
html
寫了一個與sun公司相同類名的類,加載器加載時,會自動去尋找sun公司下類的方法,結果發現,沒有show()方法,就會報錯。
java
如今寫了一個類加載器,該類加載器的做用是,指定加載哪個類(調用構造方法時會傳入調用類的地址)
ide
再經過反射得到方法的對象。
this
package sun.security.ec; public class ECDHKeyAgreement { public void show(){ System.out.println("哈哈~"); } }
package cn.itcast.classloader; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class MyClassLoader extends ClassLoader { private String rootDir; public MyClassLoader(String rootDir) { this.rootDir = rootDir; } @Override public Class<?> findClass(String name) throws ClassNotFoundException { String extname = name.replace(".", "\\"); String filename = rootDir + "\\" + extname + ".class"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { InputStream is = new FileInputStream(filename); int len = -1; byte[] b = new byte[1024]; while ((len = is.read(b)) != -1) { baos.write(b, 0, len); } baos.flush(); baos.close(); is.close(); byte[] data = baos.toByteArray(); return defineClass(name, data, 0, data.length); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
package sun.security.ec; import java.lang.reflect.Method; import cn.itcast.classloader.MyClassLoader; public class Test { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { /*ECDHKeyAgreement ea = new ECDHKeyAgreement(); ea.show();*/ MyClassLoader loader = new MyClassLoader("E:\\代碼\\160226\\day22-classloader\\bin\\"); Class<?> clazz = loader.findClass("sun.security.ec.ECDHKeyAgreement"); Method method = clazz.getMethod("show");//反射得到method對象 method.invoke(clazz.newInstance());//執行method } }
動態代理,裝飾模型的區別:http://www.cnblogs.com/jaredlam/archive/2011/11/08/2241089.htmlspa