import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
// 创建被代理类对象
SuperMan superMan = new SuperMan();
// 创建代理类对象
Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan);
proxyInstance.getBelief();
proxyInstance.eat("麻辣烫");
}
}
class HumanUtil{
public void method1() {
System.out.println("执行通用方法1。");
}
public void method2() {
System.out.println("执行通用方法2。");
}
}
interface Human{
void getBelief();
void eat(String food);
}
// 被代理类
class SuperMan implements Human{
@Override
public void getBelief() {
System.out.println("I believe I can fly!");
}
@Override
public void eat(String food) {
System.out.println("我喜欢吃" + food);
}
}
// 生产代理类的工厂
class ProxyFactory{
// 根据加载到内存中的被代理类对象,创建代理类对象
public static Object getProxyInstance(Object obj){
MyInvocationHandler handler = new MyInvocationHandler();
handler.bind(obj);
// 创建和被代理类对象同构造器,同接口的代理类对象
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), handler);
}
}
class MyInvocationHandler implements InvocationHandler{
// 被代理类的对象
private Object obj;
public void bind(Object obj) {
this.obj = obj;
}
// 代理类对象调用方法时,自动调用invoke方法(动态的调用被代理类中的同名方法)
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
HumanUtil humanUtil = new HumanUtil();
humanUtil.method1();
Object returnObj = method.invoke(obj, args);
humanUtil.method2();
return returnObj;
}
}
执行通用方法1。
I believe I can fly!
执行通用方法2。
执行通用方法1。
我喜欢吃麻辣烫
执行通用方法2。