• Dubbo SPI-Adaptive详解


    http://dubbo.apache.org/zh-cn/docs/source_code_guide/adaptive-extension.html
      在Dubbo中,很多拓展都是通过SPI机制进行加载的,比如Protocol、Cluster、LoadBalance等。

      有时,有些拓展类并不想在框架启动阶段被加载,而是希望在拓展方法被调用时,根据运行参数进行加载。

      拓展未被加载,那么拓展方法就无法被调用。拓展方法未被调用,拓展旧无法被加载。

      dubbo通过自适应拓展机制很好的解决了:首先Dubbo会为拓展接口生成具有代理功能的代码。然后通过javassist或jdk编译这段代码,得到Class类,最后通过反射创建代理类

    一、四个测试用例

      准备如下

    import com.alibaba.dubbo.common.URL;
    import com.alibaba.dubbo.common.extension.Adaptive;
    import com.alibaba.dubbo.common.extension.SPI;
    @SPI
    public interface AdaptiveExt2 {
        @Adaptive
        String echo(String msg, URL url);
    }
    三个实现类
    public class DubboAdaptiveExt2 implements AdaptiveExt2 {
        @Override
        public String echo(String msg, URL url) {
            return "dubbo";
        }
    }
    public class SpringCloudAdaptiveExt2 implements AdaptiveExt2 {
        @Override
        public String echo(String msg, URL url) {
            return "spirng cloud";
        }
    }
    public class ThriftAdaptiveExt2 implements AdaptiveExt2 {
        @Override
        public String echo(String msg, URL url) {
            return "thrift";
        }
    }

    在Resource目录下,添加/META-INF/dubbo/internal/com.example.dubbo.adaptive.AdaptiveExt2

    dubbo=com.example.dubbo.adaptive.DubboAdaptiveExt2
    cloud=com.example.dubbo.adaptive.SpringCloudAdaptiveExt2
    thrift=com.example.dubbo.adaptive.ThriftAdaptiveExt2

    测试1. SPI注解上有value值

    @SPI("dubbo")
    public interface AdaptiveExt2 {
        @Adaptive
        String echo(String msg, URL url);
    }
    @Test
        public void testdubbo(){
            // @SPI("dubbo")
            ExtensionLoader<AdaptiveExt2> loader = ExtensionLoader.getExtensionLoader(AdaptiveExt2.class);
            AdaptiveExt2 adaptiveExtension = loader.getAdaptiveExtension();
            URL url = URL.valueOf("test://loalhost/test");
            System.out.println(adaptiveExtension.echo("d",url));
        }
    结果
    dubbo

     测试2 SPI注解上有value值,URL上也有具体的值

    @SPI("dubbo")
    public interface AdaptiveExt2 {
        @Adaptive
        String echo(String msg, URL url);
    }
        @Test
        public void testdubbo2(){
            // @SPI("dubbo")
            // +?adaptive.ext2=cloud
            ExtensionLoader<AdaptiveExt2> loader = ExtensionLoader.getExtensionLoader(AdaptiveExt2.class);
            AdaptiveExt2 adaptiveExtension = loader.getAdaptiveExtension();
            URL url = URL.valueOf("test://loalhost/test?adaptive.ext2=cloud");
            System.out.println(adaptiveExtension.echo("d",url));
        }
    结果
    spirng cloud
    说明 RUL优先于SPI注解的value值
    

     测试3 SPI注解有value值,URL中也有具体的值,实现类上有@Adaptive注解

    @SPI("dubbo")
    public interface AdaptiveExt2 {
        @Adaptive
        String echo(String msg, URL url);
    }
    @Adaptive
    public class ThriftAdaptiveExt2 implements AdaptiveExt2 {
        @Override
        public String echo(String msg, URL url) {
            return "thrift";
        }
    }
        @Test
        public void testdubbo3(){
            // @Adaptive
            //public class ThriftAdaptiveExt2
            //+?adaptive.ext2=cloud
            ExtensionLoader<AdaptiveExt2> loader = ExtensionLoader.getExtensionLoader(AdaptiveExt2.class);
            AdaptiveExt2 adaptiveExtension = loader.getAdaptiveExtension();
            URL url = URL.valueOf("test://loalhost/test?adaptive.ext2=cloud");
            System.out.println(adaptiveExtension.echo("d",url));
        }
    结果
    thrift
    说明 实现类的@Adaptive注解优先于URL 
    

     测试4 SPI注解中有value值,实现类上没有@Adaptive注解,在方法上打上@Adaptive注解,注解中的value与链接中的参数key一致,

    @SPI("dubbo")
    public interface AdaptiveExt2 {
        @Adaptive({"t"})
        String echo(String msg, URL url);
    }
        @Test
        public void testdubbo4(){
            // @SPI("dubbo")
            //public interface AdaptiveExt2 {
            //    @Adaptive({"t"})
            //    String echo(String msg, URL url);
            // ?t=cloud
            ExtensionLoader<AdaptiveExt2> loader = ExtensionLoader.getExtensionLoader(AdaptiveExt2.class);
            AdaptiveExt2 adaptiveExtension = loader.getAdaptiveExtension();
            URL url = URL.valueOf("test://loalhost/test?t=cloud");
            System.out.println(adaptiveExtension.echo("d",url));
        }
    
    结果 
    spirng cloud
    

     测试结论:

      1.在类上加@Adaptive注解的类,是最明确的创建对应类型的Adaptive类。所有它的优先级最高

      2.@SPI注解的value值是默认值,如果通过URL获取不到关于取那个类作为Adaptive类的话,就是用这个默认值,当然如果URL中可以获取到,就用URL中的

      3.可以在方法上增加@Adaptive注解,注解中value与链接中的参数key一致,连接中的key对应的value就是spi中的name,获取对应的实现类

     

    源码分析:

     

    ExtensionLoader<AdaptiveExt2> loader = ExtensionLoader.getExtensionLoader(AdaptiveExt2.class);
    
      @SuppressWarnings("unchecked")
      public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
            if (type == null)
                throw new IllegalArgumentException("Extension type == null");
            if(!type.isInterface()) {
                throw new IllegalArgumentException("Extension type(" + type + ") is not interface!");
            }
            // 这个类型必须加上SPI注解,否则报错
            if(!withExtensionAnnotation(type)) {
                throw new IllegalArgumentException("Extension type(" + type + 
                        ") is not extension, because WITHOUT @" + SPI.class.getSimpleName() + " Annotation!");
            }
            // 从缓存中获取
            ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
            if (loader == null) {
                EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
                loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
            }
            return loader;
      }    
    

     

      先检查SPI注解,再缓存中查询对应ExtensionLoader,dubbo中的spi大量利用了本地缓存。

    // 构造方法私有化
      private ExtensionLoader(Class<?> type) {
            this.type = type;
           // 如果type是ExtensionFactory类型,那么objectFactory是null,否则是ExtensionFactory类型的适配器
            objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
      }    
    

      两点:

        1.构造方法私有化,不能通过外部实例化

        2.objectFactory是ioc功能

      开始获取adaptive对象

     

        @SuppressWarnings("unchecked")
        public T getAdaptiveExtension() {
            Object instance = cachedAdaptiveInstance.get();
            if (instance == null) {
                if(createAdaptiveInstanceError == null) {
                    synchronized (cachedAdaptiveInstance) {
                        instance = cachedAdaptiveInstance.get();
                        if (instance == null) {
                            try {
                                // 缓存获取不到就创建
                                instance = createAdaptiveExtension();
                                cachedAdaptiveInstance.set(instance);
                            } catch (Throwable t) {
                                createAdaptiveInstanceError = t;
                                throw new IllegalStateException("fail to create adaptive instance: " + t.toString(), t);
                            }
                        }
                    }
                }
                else {
                    throw new IllegalStateException("fail to create adaptive instance: " + createAdaptiveInstanceError.toString(), createAdaptiveInstanceError);
                }
            }
    
            return (T) instance;
        }

      第一次从缓存中获取就创建

        @SuppressWarnings("unchecked")
        private T createAdaptiveExtension() {
            try {
                return injectExtension((T) getAdaptiveExtensionClass().newInstance());
            } catch (Exception e) {
                throw new IllegalStateException("Can not create adaptive extenstion " + type + ", cause: " + e.getMessage(), e);
            }
        }

      获取到适配器类的Class,利用反射船舰适配器类的实例,injectExtension是dubbo的DI,依赖注入,如果适配器类有属性的set方法,就会自动注入。

        private Class<?> getAdaptiveExtensionClass() {
            // 触发SPI流程的扫描
            getExtensionClasses();
            // 如果通过上面的步骤可以获取到cacheAdaptiveClass直接返回,如果不行就自行利用动态代理创建一个
            if (cachedAdaptiveClass != null) {
                return cachedAdaptiveClass;
            }
            // 利用动态代理创建一个扩展类
            return cachedAdaptiveClass = createAdaptiveExtensionClass();
        }    
    

      首先先看getExtensionClasses

      private Map<String, Class<?>> getExtensionClasses() {
            Map<String, Class<?>> classes = cachedClasses.get();
            if (classes == null) {
                synchronized (cachedClasses) {
                    classes = cachedClasses.get();
                    if (classes == null) {
                        classes = loadExtensionClasses();
                        cachedClasses.set(classes);
                    }
                }
            }
            return classes;
      }
    

      从缓存中取,也就是说加载流程只触发一次,然后放入缓存,后续从缓存中取

        // 此方法已经getExtensionClasses方法同步过。
        private Map<String, Class<?>> loadExtensionClasses() {
       // 获取到类型SPI注解,所以利用SPI扩展点的地方,需要加入SPI注解 final SPI defaultAnnotation = type.getAnnotation(SPI.class); if(defaultAnnotation != null) { String value = defaultAnnotation.value(); if(value != null && (value = value.trim()).length() > 0) { String[] names = NAME_SEPARATOR.split(value); if(names.length > 1) { throw new IllegalStateException("more than 1 default extension name on extension " + type.getName() + ": " + Arrays.toString(names)); }
       // 如果注解中有value,说明有默认的实现,那么将value放到cacheDefaultName中 if(names.length == 1) cachedDefaultName = names[0]; } } // 从 META-INF/dubbo/internal/...读取数据 Map<String, Class<?>> extensionClasses = new HashMap<String, Class<?>>(); loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY); loadFile(extensionClasses, DUBBO_DIRECTORY); loadFile(extensionClasses, SERVICES_DIRECTORY); return extensionClasses; }

      获取type上SPI注解,如果里面有value值就赋值给cacheDefaultName变量,随后从META-INF/dubbo/internal/ 、META-INF/dubbo/、META-INF/services/ 这三个路径下搜索对应的文件。

      

        private void loadFile(Map<String, Class<?>> extensionClasses, String dir) {
            String fileName = dir + type.getName();
            try {
                Enumeration<java.net.URL> urls;
                ClassLoader classLoader = findClassLoader();
                if (classLoader != null) {
                    urls = classLoader.getResources(fileName);
                } else {
                    urls = ClassLoader.getSystemResources(fileName);
                }
                if (urls != null) {
                    while (urls.hasMoreElements()) {
                        java.net.URL url = urls.nextElement();
                        try {
                            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
                            try {
                                String line = null;
                                while ((line = reader.readLine()) != null) {
                       // 排除一些# 注释的内容 final int ci = line.indexOf('#'); if (ci >= 0) line = line.substring(0, ci); line = line.trim(); if (line.length() > 0) { try { String name = null;
                            // 使用 = 进行分割 name=全路径名称 int i = line.indexOf('='); if (i > 0) { name = line.substring(0, i).trim(); line = line.substring(i + 1).trim(); } if (line.length() > 0) {
                              // 加载解析出的类的全限定名称 Class<?> clazz = Class.forName(line, true, classLoader);
                              // 判断新家在的clazz是否是type的子类,不是则报错 if (! type.isAssignableFrom(clazz)) { throw new IllegalStateException("Error when load extension class(interface: " + type + ", class line: " + clazz.getName() + "), class " + clazz.getName() + "is not subtype of interface."); }
                              // 判断这个加载的类上有没有@Adaptive注解, if (clazz.isAnnotationPresent(Adaptive.class)) { if(cachedAdaptiveClass == null) {
                                    // 将此类作为cacheAdaptiveClass cachedAdaptiveClass = clazz; } else if (! cachedAdaptiveClass.equals(clazz)) {
                                    // 多个adaptive类的实例,报错 throw new IllegalStateException("More than 1 adaptive class found: " + cachedAdaptiveClass.getClass().getName() + ", " + clazz.getClass().getName()); } } else {
                                 // 如果这个类没有@Adaptive注解 try {
                                   // 查看这个类有没有此类型的构造方法(主要是为了Wrapper类使用,如果有说明是个wrapper类) clazz.getConstructor(type); Set<Class<?>> wrappers = cachedWrapperClasses; if (wrappers == null) { cachedWrapperClasses = new ConcurrentHashSet<Class<?>>(); wrappers = cachedWrapperClasses; }
                                    // 将此warpper放入warpper容器中,也就是cacheWrapperClasses里面 wrappers.add(clazz); } catch (NoSuchMethodException e) {
                                    // 不是wrapper类,就会抛出异常执行这里, clazz.getConstructor(); if (name == null || name.length() == 0) {
                                     // 如果name没有写,就是用默认规则生成一个 name = findAnnotationName(clazz); if (name == null || name.length() == 0) { if (clazz.getSimpleName().length() > type.getSimpleName().length() && clazz.getSimpleName().endsWith(type.getSimpleName())) { name = clazz.getSimpleName().substring(0, clazz.getSimpleName().length() - type.getSimpleName().length()).toLowerCase(); } else { throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + url); } } } String[] names = NAME_SEPARATOR.split(name); if (names != null && names.length > 0) {
                                        // 看下这个类上有没有@adaptive注解 Activate activate = clazz.getAnnotation(Activate.class); if (activate != null) {
                                        // 存在就在cacheAdaptivates里面添加名称与注解 cachedActivates.put(names[0], activate); } for (String n : names) { if (! cachedNames.containsKey(clazz)) {
                                          // 将此类型的实例与name放入cacheNames cachedNames.put(clazz, n); } Class<?> c = extensionClasses.get(n); if (c == null) {
                                          // 最后往wxtensionClasses添加名称与class extensionClasses.put(n, clazz); } else if (c != clazz) { throw new IllegalStateException("Duplicate extension " + type.getName() + " name " + n + " on " + c.getName() + " and " + clazz.getName()); } } } } } } } catch (Throwable t) { IllegalStateException e = new IllegalStateException("Failed to load extension class(interface: " + type + ", class line: " + line + ") in " + url + ", cause: " + t.getMessage(), t); exceptions.put(line, e); } } } // end of while read lines } finally { reader.close(); } } catch (Throwable t) { logger.error("Exception when load extension class(interface: " + type + ", class file: " + url + ") in " + url, t); } } // end of while urls } } catch (Throwable t) { logger.error("Exception when load extension class(interface: " + type + ", description file: " + fileName + ").", t); } }

      classLoader.getResources 方法获取到的Enumeration<java.net.URL>类型的对象,随后就是遍历

      dubbo=shuqi.dubbotest.spi.adaptive.DubboAdaptiveExt2
      cloud=shuqi.dubbotest.spi.adaptive.SpringCloudAdaptiveExt2
      thrift=shuqi.dubbotest.spi.adaptive.ThriftAdaptiveExt2
    如果有#,#后面就是注释,前面是业务数据
    如果有=,就按照=进行分割,前面是扩展名称,后面是扩展的全限定类名,方便利用反射加载进来
    首先判断一下是不是传入类(type)类型的实例,不是的话:报错
    如果类上有@Adaptive注解,那么将这个类赋值给擦车的AdaptiveClass,因为是系统指定的适配类,优先级最高。
      如果多个类上打了@Adaptive注解会报错,“More than 1 adaptive class found:.....”
    如果扩展类上没有打上@Adaptive注解:
      第一步:会验证有没有type这个类型作为入参的构造方法 (因为Wrapper,有的类型需要包装一下例如ProtocolFilterWoapper和ProtocolListenerWrapper)
      第二步:没有这种类型的构造方法,就是正常的type类型的实例
    如果没有声明name名称就根据类名创建一个名称
    查看类上有没有@Adaptive注解:
      有:将名称与注解放到擦车的Activates这个Map中进行缓存
    将扩展类和名称放入cachedNames这个Map中进行缓存,将名称和扩展类的class放入传递进来的extensionClsses中
    最后这个extensionClasses会被返回出来被使用。

      接下来回到getAdaptiveExtensionClss()方法
        private Class<?> getAdaptiveExtensionClass() {
            // 触发SPI流程的扫描
            getExtensionClasses();
            // 如果通过上面的步骤可以获取到cacheAdaptiveClass直接返回,如果不行就自行利用动态代理创建一个
            if (cachedAdaptiveClass != null) {
                return cachedAdaptiveClass;
            }
            // 利用动态代理创建一个扩展类
            return cachedAdaptiveClass = createAdaptiveExtensionClass();
        }  
    

      如果cachedAdaptiveClss不为空就返回,那什么情况下不为空?当扩展类打上@Adaptive注解的时候,就会直接将这个类返回。如果没有注解,就得自己生成一个也就是createAdaptiveExtensionClass

      
      private Class<?> createAdaptiveExtensionClass() {
          // 创建代码的字符串形式 String code = createAdaptiveExtensionClassCode();
          // 寻找类加载器 ClassLoader classLoader = findClassLoader();
          // 寻找Compiler的适配器扩展类 com.alibaba.dubbo.common.compiler.Compiler compiler = ExtensionLoader.getExtensionLoader(com.alibaba.dubbo.common.compiler.Compiler.class).getAdaptiveExtension();  // 进行编译成class的实例返回
         return compiler.compile(code, classLoader); }

      将类以字符串的形式拼接出来,然后利用编译器进行编译,返回编译后的class对象。

      /**
      * 创建适配器的扩展类的string
      */
      private String createAdaptiveExtensionClassCode() {
            StringBuilder codeBuidler = new StringBuilder();
          // 获取这个类的所有方法 Method[] methods = type.getMethods(); boolean hasAdaptiveAnnotation = false; for(Method m : methods) {
            // 遍历方法,如果有方法上@Adaptive注解 if(m.isAnnotationPresent(Adaptive.class)) { hasAdaptiveAnnotation = true; break; } } // 完全没有Adaptive方法,则不需要生成Adaptive类 if(! hasAdaptiveAnnotation) throw new IllegalStateException("No adaptive method on extension " + type.getName() + ", refuse to create the adaptive class!"); codeBuidler.append("package " + type.getPackage().getName() + ";"); codeBuidler.append(" import " + ExtensionLoader.class.getName() + ";"); codeBuidler.append(" public class " + type.getSimpleName() + "$Adpative" + " implements " + type.getCanonicalName() + " {"); for (Method method : methods) { Class<?> rt = method.getReturnType(); Class<?>[] pts = method.getParameterTypes();//获取参数列表的类型 Class<?>[] ets = method.getExceptionTypes();//异常列表的类型         // 获得Adaptive的注解 Adaptive adaptiveAnnotation = method.getAnnotation(Adaptive.class); StringBuilder code = new StringBuilder(512);
            // 如果这个方法没有注解,添加不支持调用此方法的异常 if (adaptiveAnnotation == null) { code.append("throw new UnsupportedOperationException("method ") .append(method.toString()).append(" of interface ") .append(type.getName()).append(" is not adaptive method!");"); } else { int urlTypeIndex = -1;
              // 寻找列表中类型是URL.class,记录它的位置,数据放到urlTypeIndex中 for (int i = 0; i < pts.length; ++i) { if (pts[i].equals(URL.class)) { urlTypeIndex = i; break; } } // 有类型为URL的参数 if (urlTypeIndex != -1) { // Null Point check String s = String.format(" if (arg%d == null) throw new IllegalArgumentException("url == null");", urlTypeIndex); code.append(s); s = String.format(" %s url = arg%d;", URL.class.getName(), urlTypeIndex); code.append(s); } // 参数没有URL类型 else { String attribMethod = null; // 找到参数的URL属性 LBL_PTS: for (int i = 0; i < pts.length; ++i) { Method[] ms = pts[i].getMethods(); for (Method m : ms) { String name = m.getName(); if ((name.startsWith("get") || name.length() > 3) && Modifier.isPublic(m.getModifiers()) && !Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0 && m.getReturnType() == URL.class) { urlTypeIndex = i; attribMethod = name; break LBL_PTS; } } } if(attribMethod == null) { throw new IllegalStateException("fail to create adative class for interface " + type.getName() + ": not found url parameter or url attribute in parameters of method " + method.getName()); } // Null point check String s = String.format(" if (arg%d == null) throw new IllegalArgumentException("%s argument == null");", urlTypeIndex, pts[urlTypeIndex].getName()); code.append(s); s = String.format(" if (arg%d.%s() == null) throw new IllegalArgumentException("%s argument %s() == null");", urlTypeIndex, attribMethod, pts[urlTypeIndex].getName(), attribMethod); code.append(s); s = String.format("%s url = arg%d.%s();",URL.class.getName(), urlTypeIndex, attribMethod); code.append(s); } // 获取Adaptive设置的value String[] value = adaptiveAnnotation.value(); // 没有设置Key,则使用“扩展点接口名的点分隔 作为Key if(value.length == 0) { char[] charArray = type.getSimpleName().toCharArray(); StringBuilder sb = new StringBuilder(128); for (int i = 0; i < charArray.length; i++) { if(Character.isUpperCase(charArray[i])) { if(i != 0) { sb.append("."); } sb.append(Character.toLowerCase(charArray[i])); } else { sb.append(charArray[i]); } } value = new String[] {sb.toString()}; } boolean hasInvocation = false;
              // 如果参数列表中有Invocation的实例 for (int i = 0; i < pts.length; ++i) { if (pts[i].getName().equals("com.alibaba.dubbo.rpc.Invocation")) { // Null Point check String s = String.format(" if (arg%d == null) throw new IllegalArgumentException("invocation == null");", i); code.append(s); s = String.format(" String methodName = arg%d.getMethodName();", i); code.append(s); hasInvocation = true; break; } } // defaultExtName位注解中的value String defaultExtName = cachedDefaultName; String getNameCode = null; for (int i = value.length - 1; i >= 0; --i) { if(i == value.length - 1) { if(null != defaultExtName) { if(!"protocol".equals(value[i])) if (hasInvocation) getNameCode = String.format("url.getMethodParameter(methodName, "%s", "%s")", value[i], defaultExtName); else getNameCode = String.format("url.getParameter("%s", "%s")", value[i], defaultExtName); else getNameCode = String.format("( url.getProtocol() == null ? "%s" : url.getProtocol() )", defaultExtName); } else { if(!"protocol".equals(value[i])) if (hasInvocation) getNameCode = String.format("url.getMethodParameter(methodName, "%s", "%s")", value[i], defaultExtName); else getNameCode = String.format("url.getParameter("%s")", value[i]); else getNameCode = "url.getProtocol()"; } } else { if(!"protocol".equals(value[i])) if (hasInvocation) getNameCode = String.format("url.getMethodParameter(methodName, "%s", "%s")", value[i], defaultExtName); else getNameCode = String.format("url.getParameter("%s", %s)", value[i], getNameCode); else getNameCode = String.format("url.getProtocol() == null ? (%s) : url.getProtocol()", getNameCode); } } code.append(" String extName = ").append(getNameCode).append(";"); // check extName == null? String s = String.format(" if(extName == null) " + "throw new IllegalStateException("Fail to get extension(%s) name from url(" + url.toString() + ") use keys(%s)");", type.getName(), Arrays.toString(value)); code.append(s); s = String.format(" %s extension = (%<s)%s.getExtensionLoader(%s.class).getExtension(extName);", type.getName(), ExtensionLoader.class.getSimpleName(), type.getName()); code.append(s); // return statement if (!rt.equals(void.class)) { code.append(" return "); } s = String.format("extension.%s(", method.getName()); code.append(s); for (int i = 0; i < pts.length; i++) { if (i != 0) code.append(", "); code.append("arg").append(i); } code.append(");"); } codeBuidler.append(" public " + rt.getCanonicalName() + " " + method.getName() + "("); for (int i = 0; i < pts.length; i ++) { if (i > 0) { codeBuidler.append(", "); } codeBuidler.append(pts[i].getCanonicalName()); codeBuidler.append(" "); codeBuidler.append("arg" + i); } codeBuidler.append(")"); if (ets.length > 0) { codeBuidler.append(" throws "); for (int i = 0; i < ets.length; i ++) { if (i > 0) { codeBuidler.append(", "); } codeBuidler.append(pts[i].getCanonicalName()); } } codeBuidler.append(" {"); codeBuidler.append(code.toString()); codeBuidler.append(" }"); } codeBuidler.append(" }"); if (logger.isDebugEnabled()) { logger.debug(codeBuidler.toString()); } return codeBuidler.toString(); }

       首先寻找这个类中所有的方法,查看方法中有没有打@Adaptive注解的,一个没有,直接报错,对于哪些没有加@Adaptive的方法,直接在要创建的Adaptive类上添加此方法不支持操作的异常。在方法中的注解上可以添加value值,如果填写了,使用此值,没有添加将更具类名创建的值作为value值。

    public class AdaptiveExt2$Adpative implements shuqi.dubbotest.spi.adaptive.AdaptiveExt2 {
        public java.lang.String echo(java.lang.String arg0, com.alibaba.dubbo.common.URL arg1) {
            if (arg1 == null) throw new IllegalArgumentException("url == null");
            com.alibaba.dubbo.common.URL url = arg1;
            String extName = url.getParameter("t", "dubbo");
            if (extName == null)
                throw new IllegalStateException("Fail to get extension(shuqi.dubbotest.spi.adaptive.AdaptiveExt2) name from url(" + url.toString() + ") use keys([t])");
            shuqi.dubbotest.spi.adaptive.AdaptiveExt2 extension = (shuqi.dubbotest.spi.adaptive.AdaptiveExt2) ExtensionLoader.getExtensionLoader(shuqi.dubbotest.spi.adaptive.AdaptiveExt2.class).getExtension(extName);
            return extension.echo(arg0, arg1);
        }
    }
    

      

      

     

      

     

  • 相关阅读:
    LoadRunner11 问题记录
    安装依赖包时,编译提示依赖库未安装,但实际上已经安装
    Close_wait进程过多
    JS中的混合模式
    JS面相对象
    JS中的工厂模式
    函数式编程Map()&Reduce()
    JavaScript函数参数与调用
    JavaScript中的prototype
    循环
  • 原文地址:https://www.cnblogs.com/huan30/p/12769683.html
Copyright © 2020-2023  润新知