Java动态代理
一、定义一个接口
public interface Plane {
public void fly();
}
二、实现接口中的方法
public class ManagerImpl implements Plane{
@Override
public void fly() {
System.out.println("飞机起飞了");
}
}
三、
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class BusinessHandler implements InvocationHandler{
private Object object = null;
public BusinessHandler(Object object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("do something before method");
Object ret = method.invoke(this.object, args);
System.out.println("do something after method");
return ret;
}
}
四、
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
ManagerImpl managerImpl = new ManagerImpl();
// 业务代理类
BusinessHandler securityHandler = new BusinessHandler(managerImpl);
// 获得代理类($Proxy0 extends Proxy implements Manager)的实例.
Plane managerProxy = (Plane) Proxy.newProxyInstance(
managerImpl.getClass().getClassLoader(), managerImpl.getClass().getInterfaces(), securityHandler);
managerProxy.fly();
}
}