动态代理代码实例
package com.atguigu.java;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Human{
String belief();
void eat();
}
class SuperHuman implements Human{
@Override
public String belief() {
return "I can fly!";
}
@Override
public void eat() {
System.out.println("我爱吃四川麻辣烫!");
}
}
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;
}
@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) {
SuperHuman superHuman = new SuperHuman();
Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superHuman);
System.out.println(proxyInstance.belief());
proxyInstance.eat();
}
}