沒有接口實現類代理

問題的提出

正常的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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章