Proxy
Proxy
提供了创建动态代理类和实例的静态方法,比如Proxy.newProxyInstance
这个方法就可以用来创建代理实例,而Proxy
也是由这些方法创建的所有动态代理的超类。
- 接口InvocationHandler
每个代理实例都有一个关联的调用处理程序对象,比如,本例的MyInvocationHandler
就是调用处理程序,该处理程序实现了接口InvocationHandler
。 - new newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)
通过调用Proxy.newProxyInstance
方法来创建代理实例,每个代理实例都有一个关联的调用处理程序,该处理程序被传递给代理实例的构造函数。
InvocationHandler
InvocationHandler
是由代理实例的调用处理程序实现的接口。
每个代理实例都有一个关联的调用处理程序。当代理对象调用方法时,将在调用处理程序中调用invoke
方法。
实例1
- UserService
public interface UserService {
void getUser();
}
- UserServiceImpl
public class UserServiceImpl implements UserService{
@Override
public void getUser() {
System.out.println("getting user now!");
}
}
- MyInvocationHandler
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocationHandler implements InvocationHandler {
private UserService userService;
public MyInvocationHandler(UserService userService) {
this.userService = userService;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log("getUser");
return method.invoke(userService,args);
}
public void log(String methodName){
System.out.println("Executing Method:" + methodName);
}
}
- Test
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
MyInvocationHandler handler = new MyInvocationHandler(userService);
UserService proxy = (UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(), userService.getClass().getInterfaces(),handler);
proxy.getUser();
}
}
- 测试验证
实例2
- RentService
package com.jepcc.demo;
public interface RentService {
void rent();
}
- Host
public class Host implements RentService{
@Override
public void rent() {
System.out.println("房屋出租");
}
}
- RentInvocationHandler
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class RentInvocationHandler implements InvocationHandler {
private RentService rentService;
public void setRentService(RentService rentService) {
this.rentService = rentService;
}
public Object getProxy(){
return Proxy.newProxyInstance(rentService.getClass().getClassLoader(), rentService.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
show();
Object result = method.invoke(rentService,args);
fee();
return result;
}
public void show(){
System.out.println("带客户看房");
}
public void fee(){
System.out.println("收取中介费");
}
}
- Client
public class Client {
public static void main(String[] args) {
Host host = new Host();
RentInvocationHandler handler = new RentInvocationHandler();
handler.setRentService(host);
RentService proxy = (RentService) handler.getProxy();
proxy.rent();
}
}
- 测试验证