静态代理和动态代理 静态代理,其实就是方法的重写,原来的方法不能满足现有的需求,需要重写一个方法,来取代原来的方法。动态代理,proxy.newProxyInstance(需要代理类的类加载器user.getClass().getClassLoader(),需要代理类实现的接口user.getClass().getClassInterfaces(),调用方法InvocationHander()里面是代理的具体操作。 public class MainTest {
public static void main(String[] args) {
final User man = new Man();//fianl表示man只能实例化一次
//invocation调用
User manProxy = (User) Proxy.newProxyInstance(man.getClass().getClassLoader(), man.getClass().getInterfaces(), new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//相当于重写方法
if(method.getName().equals(“eat”)) {
System.out.println(“吃前”);
method.invoke(man, args);
System.out.println(“吃后”);
//invoke调用
return null;
}
return null;
}
});
manProxy.eat();
}
}