JDK动态代理,运用反射的机制
基于接口的动态代理
代理类是动态生成的
接口
被代理类(实现接口)
代理类(动态生成)
package com.interview.designpattern.proxy.dp;
/**
* <p>
* 目标接口
* </p>
*
* @author Lcp
* @version V1.0
* @since 2021/6/25 13:07
*/
public interface TargetInterface {
public void doSomething();
}
package com.interview.designpattern.proxy.util;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* <p>
* JDK动态代理:
* 生成代理对象的工具类
* </p>
*
* @author Lcp
* @version V1.0
* @since 2021/6/25 12:23
*/
public class ProxyInvocationHandler implements InvocationHandler {
// 被代理类
Object target;
public ProxyInvocationHandler(Object target) {
this.target = target;
}
// 生成被代理类方法
public Object getProxy() {
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
}
// 执行代理类调用程序的方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 可以在此处进行方法增强
beforeLog("before");
Object result = method.invoke(target, args);
afterLog("after");
return result;
}
public void beforeLog(String msg) {
System.out.println("执行前打印日志: " + msg);
}
public void afterLog(String msg) {
System.out.println("执行后打印日志: " + msg);
}
}
package com.interview.designpattern.proxy.dp;
import com.interview.designpattern.proxy.util.ProxyInvocationHandler;
/**
* @author Lcp
* @version V1.0
* @since 2021/6/25 13:05
*/
public class Jdk_03 {
public static void main(String[] args) {
// 被代理类
TheAgent agent = new TheAgent("被代理类的名称");
// 创建代理类
ProxyInvocationHandler pih = new ProxyInvocationHandler(agent);
TargetInterface proxy = (TargetInterface) pih.getProxy();
proxy.doSomething();
}
}
// 被代理类
class TheAgent implements TargetInterface {
String name;
public TheAgent(String name) {
this.name = name;
}
@Override
public void doSomething() {
System.out.println("dooooooooooo SOMEThing!");
}
}