没有接口实现类代理

问题的提出

正常的jdk动态代理和cglib代理都是通过传入实体类实现的,dubbo的消息提供者是没有接口的实现类的,那怎么实现的?

实现

接口

package com.proxynoimpl;

/**
 * @author CBeann
 * @create 2020-03-09 17:37
 */
public interface IEmailService {

    String selectById();
}

代理工厂

package com.proxynoimpl;

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

/**
 * @author CBeann
 * @create 2020-03-09 17:37
 */
public class FactoryProxy<T> implements InvocationHandler {

    private Class<T> proxyInterface;
    //这里可以维护一个缓存,存这个接口的方法抽象的对象



    FactoryProxy(Class<T> proxyInterface){
        this.proxyInterface = proxyInterface;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getName().equals("selectById")){
            //String result = (String) method.invoke(proxyInterface,args);
            //这里可以得到方法抽象对象来调用真的的查询方法
            System.out.println("selectById调用成功");
        }
        return null;
    }

    public T getProxy(){
        return (T) Proxy.newProxyInstance(proxyInterface.getClassLoader(),new Class[]{proxyInterface},this);
    }
}

测试类

package com.proxynoimpl;

/**
 * @author CBeann
 * @create 2020-03-09 17:38
 */
public class AppStart {

    public static void main(String[] args) {
        FactoryProxy<IEmailService> emailService = new FactoryProxy(IEmailService.class);
        IEmailService subject2 = emailService.getProxy();
        subject2.selectById();
    }
}

测试结果

参考

https://blog.csdn.net/a907691592/article/details/95354063

发布了99 篇原创文章 · 获赞 115 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/qq_37171353/article/details/104757500
今日推荐