Can not cast to exception in URLClassLoader

Phenomenon

When using URLClassLoader for remote class loading, sometimes when it is forced to cast, it is found that the same class is obviously used, and the force will fail, similar to com.abc.demo.ClassA can not cast to com.abc.demo .ClassA.

reason

This is because when URLClassLoader is used for remote loading, it is inconsistent with the loader (ClassLoader) that loads the class itself and the class in memory. If you use URLClassLoader without specifying the parent class loader, all classes will be loaded with URLClassLoader, and when the parent class loader is specified, the parent class loader will be used first to load, if there is no such class, URLClassLoader will be used to load

solution

When using URLClassLoader to record a class, specify the parent class loader (parent-class loader, the sentence is behind the parent).

URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{
    
    url}, this.getClass().getClassLoader());

Remote loading jar package example

        File jarFile = new File(deviceProtocol.getProtocolUrl());
        URL url;
        try {
    
    
            url = jarFile.toURI().toURL();
        } catch (Exception e) {
    
    
            throw new ServiceException("URL错误,加载不到jar");
        }
        if (null != url) {
    
    
            try {
    
    
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{
    
    url}, this.getClass().getClassLoader());
                Class<?> codec = urlClassLoader.loadClass(deviceProtocol.getMainClass());
                Object instance = codec.getClass().forName(deviceProtocol.getMainClass(), true, urlClassLoader).newInstance();
                Method method = codec.getMethod("create");
                // 加载协议包,创建实体对象
                ProtocolSupport protocolSupport = (ProtocolSupport) method.invoke(instance);
                if (!StringUtils.equals(protocolSupport.getId(), deviceProtocol.getProtocolId())) {
    
    
                    throw new ServiceException("jar包内定义的ID与协议ID不匹配");
                }
                memoryProtocolSupportRegistry.publishProtocol(protocolSupport);
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
    
    
                throw new ServiceException("jar包解析异常");
            }
        }

Guess you like

Origin blog.csdn.net/baidu_29609961/article/details/127210297