問題的提出
正常的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();
}
}
測試結果