java学习

java学习

 

Java的动态代理例子

Java的动态代理是为了拦截目标方法,例子:
public interface Person {
String sing(String name);
String dance(String name);
}
public class Liyuchun implements Person {
public String sing(String name){
System.out.println("唱" + name +"歌");
return "唱" + name +"歌";
}
public String dance(String name){
System.out.println("跳"+name+"舞");
return "跳"+name+"舞";
}
}
public class LiyuchunProxy {
private Person person ;
public Person createProxy(Person p){
this.person=p;
return (Person) Proxy.newProxyInstance(LiyuchunProxy.class.getClassLoader(), person.getClass().getInterfaces(), new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
String methodName = method.getName();
if(methodName.equals("sing")){
return method.invoke(person, args);
}else if(methodName.equals("dance")){
return method.invoke(person, args);
}else{
System.out.println("不支持");
return null;
}
}
});
}
}
public class ProxyTest {
public static void main(String[] args) {
Liyuchun cun = new Liyuchun();
LiyuchunProxy liyuchunProxy = new LiyuchunProxy();
Person person = liyuchunProxy.createProxy(cun);
String result =  person.dance("机械");
System.out.println(result);
}
}

posted on 2017-08-16 17:06 杨军威 阅读(89) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜