芝麻_糊

导航

java动态代理的实现

1.首先定义一个委托类的接口Subject,应该必须是接口,而不能是抽象类。因为Proxy.newProxyInstance方法的第二个参数需要委托类实现的接口。
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
第一个参数是代理类的类加载器
第三个参数是指明产生的代理类所做的事情,代理对象调用的任何方法都会调用 InvocationHandler 的 invoke() 方法的
2.具体委托类Connection实现Subject接口
3.代理类ConnectionProxy
package com.huyanxia.designModel;
import java.lang.reflect.*;
import java.lang.reflect.Proxy;

/**
* Created by huyanxia on 2017/8/8.
*/
interface Subject{
void query();
}
class Connection implements Subject{
public void query(){
System.out.println("查询");
}
}
class ConnectionProxy{
public Subject getProxy(){
//持有具体委托类的一个对象
Connection c = new Connection();
//返回代理对象
return (Subject) Proxy.newProxyInstance(ConnectionProxy.class.getClassLoader(), c.getClass().getInterfaces(), new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(method.getName()=="query"){
return method.invoke(c,args);
}
return null;
}
});
}
}
public class ProxyHandler {
public static void main(String[] args) {
ConnectionProxy cp = new ConnectionProxy();
cp.getProxy().query();
}
}

posted on 2017-08-09 16:48  芝麻_糊  阅读(370)  评论(0编辑  收藏  举报