是一种设计模式。通过代理访问目标对象,扩展对象的功能,多余的功能交给代理实现
1.静态代理
定义interface与Impl,代理实现interface,通过代理实现impl对象
可以在不修改目标类的前提下,对目标进行扩展
public class PeopleHandler implements InvocationHandler {
private Object obj;
public PeopleHandler(Object obj) {
this.obj = obj;
}
public Object getProxy(Object obj) {
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before invoke...");
Object result = method.invoke(obj, args);
System.out.println("after invoke...");
return result;
}
}
PeopleHandler(Object obj):通过被代理对象创建handler;
getProxy(Object obj):通过被代理对象创建代理;
invoke(Object proxy, Method method, Object[] args):代理不直接调用invoke,而是使用正常的方法时都会走invoke方法;
public class TestProxy {
public static void main(String[] args) {
//1.直接调用
System.out.println("直接调用:");
People people = new Student();
people.work();
//2.通过代理调用
System.out.println("\n通过代理调用:");
PeopleHandler handler = new PeopleHandler(people);
People proxy = (People) handler.getProxy(people);
proxy.work();
}
}
2.动态代理
动态代理不需要实现接口
利用JDK的API,在内存中构建对象 java.lang.reflect.Proxy, 使用newProxyInstance方法
//给目标对象生成代理对象
public Object getProxyInstance() {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("开始事务2");
//执行目标对象方法
Object returnValue = method.invoke(target, args);
System.out.println("提交事务2");
return returnValue;
}
}
);
Cglib代理
当代理类没有实现接口时,可以使用子类代理