1\被代理类
package com.gyarmy.proxy; public class Liyuchun implements Person { @Override public String sing(String name) { // TODO Auto-generated method stub System.out.println("李宇春 唱歌..."+name); return "sing over"; } @Override public String dance(String name) { // TODO Auto-generated method stub System.out.println("李宇春 跳舞.."+name); return "dance over"; } }
2\代理类
package com.gyarmy.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyLiyuchun { private Liyuchun chunchun = new Liyuchun(); public Object getProxy() { //设计代理类 Person proxyChunchun = (Person)Proxy.newProxyInstance(ProxyLiyuchun.class.getClassLoader(), Liyuchun.class.getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getName().equals("sing")){ //说明调用的是 sing 方法, 现在是向 让 chunchun 去唱歌了 // 让真实的 chunchun 去唱歌 System.out.println("拿 1 万 刀 来 ...."); return method.invoke(chunchun, args); // chunchun.sing(); }else if(method.getName().equals("dance")){ System.out.println("拿两万刀 来 ..."); return method.invoke(chunchun, args); // chunchun.dance(); }else{ System.out.println("春哥没这个服务..."); return null; } } }); return proxyChunchun; } }
3\测试使用
package com.gyarmy.proxy; import org.junit.Test; public class demoProxy { @Test public void test1() { ProxyLiyuchun p = new ProxyLiyuchun(); Person li = (Person)p.getProxy(); String sing = li.sing("多多"); System.out.println(sing); String dance = li.dance("fuck"); System.out.println(dance); //li.hashCode(); } }
0则评论给“动态代理简单测试”