【动态代理】JDK实现的Demo

57 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第1天,点击查看活动详情

JDK实现动态代理基本就两步:

  1. 调用Proxy#newProxyInstance(...)方法,传入所需参数
  2. 定制需要对被代理对象进行操作的InvocationHandler实现类

需要被代理的接口

public interface MyInterface {
    void sayHello(String str);
}

代理操作

public class testJDK {
    public static void main(String[] args) {
        MyInterface impl = (MyInterface)Proxy.newProxyInstance(MyInterface.class.getClassLoader(),
                                                                new Class[]{MyInterface.class},
                                                                new sayHelloInvocationHandler());
        impl.sayHello("hello");
    }
}
class sayHelloInvocationHandler implements InvocationHandler{
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(args);
        System.out.println(args[0]);
        // 使用Proxy#newProxyInstance(...)方法传入的类不是可实例化的时候(接口或抽象类),
        // 不能调用method#invoke(...) 方法
        // method.invoke(args[0]); object is not an instance of declaring class
        return null;
    }
}

\