Human.java
public interface Human {
String getBelief();
void eat(String food);
}
HumanUtil.java
public class HUmanUtil {
public void method1(){
System.out.println("*********通用方法一**************");
}
public void method2(){
System.out.println("*********通用方法二**************");
}
}
SuperMan.java
public class SuperMan implements Human{
@Override
public String getBelief() {
System.out.println("getBelief called");
return "I believe I can fly!";
}
@Override
public void eat(String food) {
System.out.println("我喜欢吃" + food);
}
}
AutoproxyTest.java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
class ProxyFactory {
//obj 被代理类的对象
public static Object getProxyInstance(Object obj) {
MyInvocationHandler handler = new MyInvocationHandler();
handler.binder(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler);
}
}
class MyInvocationHandler implements InvocationHandler {
private Object obj;
public void binder(Object obj) {
this.obj = obj;
}
//当我们通过代理类的对象,调用方法a时就会自动地调用如下方法:invoke()
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
HUmanUtil util = new HUmanUtil();
util.method1();
Object invoke = method.invoke(obj, args);
util.method2();
//上述方法的返回值就作为当前类中invoke()的返回值
return invoke;
}
}
public class AutoproxyTest {
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("************************");
}
}