Java动态代理

比如现在有一个接口及其实现类:

public interface StudentInterface {
    void eat(String food);
    void study();
}
public class Student implements StudentInterface{
    public void study() {
        System.out.println("学Java");
    }

    public void eat(String food) {
        System.out.println("吃" + food);
    }
}

student类实现了studentInterface接口的两个方法:一个eat和一个study。这是通常编写代码的方法。

现在需要对study方法进行修改,通过动态代理的方式可以无需修改student类就可以改变study方法。

通过JDK提供的一个Proxy.newProxyInstance()创建一个代理对象:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class test {
    public static void main(String[] args) {
        Student stu = new Student();

        StudentInterface proxyStu = (StudentInterface) Proxy.newProxyInstance(
                stu.getClass().getClassLoader(),
                new Class[]{StudentInterface.class},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        if (method.getName().equals("study")) {
                            System.out.println("学python");
                            return null;
                        } else {
                            return method.invoke(stu, args);
                        }
                    }
                }
        );
        proxyStu.study();
    }
}

Proxy.newProxyInstance()有三个参数:

  1. student类的ClassLoader
  2. 需要实现的接口数组,至少需要传入一个接口进去;
  3. InvocationHandler实例;

动态代理是利用Java的反射机制,Proxy.newProxyInstance创建了一个代理对象,当我们通过代理对象调用一个方法时候,这个方法的调用就会被转发到实现InvocationHandler接口类的invoke方法来调用。

proxy:代理类代理的真实代理对象

method:我们所要调用某个对象真实的方法的Method对象

args:指代代理对象方法传递的参数

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值