深入分析JDK动态代理为什么只能使用接口

本文深入剖析JDK动态代理机制,解释为何只能代理接口及如何通过Proxy.newProxyInstance调用自定义InvocationHandler的invoke方法。从源码层面揭示代理类生成过程,包括字节码重组及加载至JVM。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

初学JDK代理时,我们只知道调用一段构造方法Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h),传入接口,就能自动调用到我们实现的InvocationHandler的invoke方法中。
那么为什么只能使用接口和怎么调用到InvocationHandler的invoke方法中的呢?下面来分析下

  • 首先从Proxy.newProxyInstance看起
  @CallerSensitive
    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
   
   
        Objects.requireNonNull(h);

        final Class<?>[] intfs = interfaces.clone();
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
   
   
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }

        /*
         * Look up or generate the designated proxy class.
         */
         //生成增强之后的class
        Class<?> cl = getProxyClass0(loader, intfs);

        /*
         * Invoke its constructor with the designated invocation handler.
         */
        try {
   
   
            if (sm != null) {
   
   
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }

            final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            if (!Modifier.isPublic(cl.getModifiers())) {
   
   
                AccessController.doPrivileged(new PrivilegedAction<Void>() {
   
   
                    public Void run() {
   
   
                        cons.setAccessible(true);
                        return null;
                    }
                });
            }
            return cons.newInstance(new Object[]{
   
   h});
        } catch (IllegalAccessException|InstantiationException e) {
   
   
            throw new InternalError(e.toString(), e);
        } catch (InvocationTargetException e) {
   
   
            Throwable t = e.getCause();
            if (t instanceof RuntimeException) {
   
   
                throw (RuntimeException) t;
            } else {
   
   
                throw new InternalError(t.toString(), t);
            }
        } catch (NoSuchMethodException e) {
   
   
            throw new InternalError(e.toString(), e);
        }
    }
  • 调用getProxyClass0
private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
   
   
        if (interfaces.length > 65535) {
   
   
            throw new IllegalArgumentException("interface limit exceeded");
        }

        // If the proxy cl
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值