1.创建一个接口
package Mydynamicproxy1;public interface Star {public abstract String sing(String str);public abstract void dance(String str);
}
2.创建一个BigStar类,要实现Star这个接口
package Mydynamicproxy1;public class BigStar implements Star{private String num;@Overridepublic String sing(String song){System.out.println("正在唱歌"+song);return "唱完了谢谢";}@Overridepublic void dance(String dan){System.out.println("正在跳舞"+dan);}public BigStar() {}public BigStar(String num) {this.num = num;}/*** 获取* @return num*/public String getNum() {return num;}/*** 设置* @param num*/public void setNum(String num) {this.num = num;}public String toString() {return "BigStar{num = " + num + "}";}
}
3.代理的类
package Mydynamicproxy1;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;public class ProxyUtil {public static Star createStar(BigStar bigstar) {Star star = (Star)Proxy.newProxyInstance(ProxyUtil.class.getClassLoader(),new Class[]{Star.class},new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {if("sing".equals(method.getName())){System.out.println("准备话筒,收钱");}else{System.out.println("准备场地,收钱");}return method.invoke(bigstar, args);}});return star;}}
4.Test类
package Mydynamicproxy1;public class Test {public static void main(String[] args) {BigStar bigStar=new BigStar("cxk");Star proxy=ProxyUtil.createStar(bigStar);System.out.println(proxy.sing("aaa"));}
}