说明:如图所示,对象被代理,首先要用定义一个接口概括其所有方法,以供代理识别并进行调用;其次,代理需要implements InvocationHandler,这样才能对对象进行包装。最后使用时,是通过对象的概括接口进行调用。
1.创建对象
创建Service类
public class Service implements InterService{
public void say() {
System.out.println("我是服务对象");
}
@Override
public void say(String a) {
System.out.println(a);
}
public void say1(String a) {
System.out.println(a);
}
}
2.创建概括对象所有方法的接口
public interface InterService {
void say();
void say(String a);
}
3.创建代理对象并继承接口InvocationHandler
public class ServiceProxy implements InvocationHandler{
private Object s;
public ServiceProxy(Object s) {
this.s = s;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("动态代理处理开始");//这里可以定义所有被代理对象需要外包装的操作。
proxy=s;
method.invoke(s, args);
System.out.println("动态代理处理结束");
return null;
}
4.调用语句
Service s1=new Service(); //被代理对象
InvocationHandler s=new ServiceProxy(s1); //将对象传入Handler
InterService Inter=(InterService) Proxy.newProxyInstance(s1.getClass().getClassLoader(),
s1.getClass().getInterfaces(), s);//通过对象的方法接口将对象加载进去
Inter.say("实现他"); //调用