问题遇到的现象和发生背景
java动态代理设计模式中bind方法的作用
问题相关代码,请勿粘贴截图
package com.chang.java;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author Cao Longchang
* @create 2022-06-22 16:34
*/
// 共同接口
interface Human {
String getBelief();
void eat(String food);
}
// 被代理类
class SuperMan implements Human {
@Override
public String getBelief() {
return "I believe that I can fly!";
}
@Override
public void eat(String food) {
System.out.println("我喜欢吃" + food + "!");
}
}
// 动态代理类
class ProxyFactory {
// 调用此方法返回代理类对象。obj为被代理类对象
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 {
// obj为被代理类对象的引用
private Object obj;
public void bind(Object obj) {
this.obj = obj;
}
// 动态调用被代理类的方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(obj, args);
}
}
public class ProxyTest {
public static void main(String[] args) {
SuperMan superMan = new SuperMan();
// proxyInstance为代理类对象
Human proxyInstance = (Human)ProxyFactory.getProxyInstance(superMan);
String belief = proxyInstance.getBelief();
System.out.println(belief);
proxyInstance.eat("四川麻辣烫");
System.out.println("-----------------------------------------");
// 动态代理2
NikeClothFactory nikeClothFactory = new NikeClothFactory();
ClothFactory proxyClothFactory = (ClothFactory) ProxyFactory.getProxyInstance(nikeClothFactory);
proxyClothFactory.produceCloth();
}
}
运行结果及报错内容
运行正常
我的解答思路和尝试过的方法
把代码敲出来了,但是不知道为什么要写这个bind方法
我想要达到的结果
如上所述,感谢!