代理
- 通过代理类完成全部代理
动态代理
关于Proxy.newProxyInstance和InvocationHandler
- newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)是用于动态生成代理类。
- 参数:
1.loader: 类加载器
2.interfaces:动态代理类需要实现的接口
3.h:动态代理方法在执行时,会调用h里面的invoke方法去执行。
InvocationHandler
-
我们可以把InvocationHandler理解为对目标类进行增强,用来处理这些增强逻辑的类。代理类会调用InvocationHandler的invoke()方法,执行增强逻辑。
-
invoke()方法参数:
1.proxy:就是代理对象,newProxyInstance()方法的返回对象
2.method:调用的方法
3.args: 方法中的参数
interface Human{
String get();
void eat(String food);
}
class Person implements Human{
@Override
public String get() {
return "我是个正常人";
}
@Override
public void eat(String food) {
System.out.println("我喜欢吃" + food);
}
}
class ProxyFactory{
public static Object getproxyInstance(Object object){
// java.lang.reflect.Proxy,
MyInvocationHander myInvocationHander = new MyInvocationHander();
myInvocationHander.bind(object);
return Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),myInvocationHander);
}
}
class MyInvocationHander implements InvocationHandler{
//
private Object object;
public void bind(Object object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(object,args);
}
}
public class Test2 {
public static void main(String[] args) {
Human human = (Human) ProxyFactory.getproxyInstance(new Person());
human.eat("火锅");
System.out.println(human.get());
}
}
静态代理
- 代理类和被代理类在编译时就已经确定了
interface Factory{
void production();
}
// 代理类
class proxy implements Factory{
private Factory factory;
public proxy(Factory factory) {
this.factory = factory;
}
@Override
public void production() {
System.out.println("代理工厂在做准备工作");
factory.production();
System.out.println("代理工厂在做收尾工作");
}
}
// 被代理类
class Nike implements Factory{
@Override
public void production() {
System.out.println("NIKE正在生产");
}
}
public class Test1 {
public static void main(String[] args) {
// 创建被代理类对象
Nike nike = new Nike();
// 创建代理类
proxy proxy = new proxy(nike);
proxy.production();
}
}