记录jar包解析

方式一: 从接口到文件服务器下载jar包到本地服务器,并解析jar包

            // 文件服务器地址通过接口方式下载,jar包
            String fileId = "http://192.168.20.200:端口号/xxx/xxx/xxx.jar";
            // 本地下载文件
            // String fileId = "/xxx/xxx/xxx.jar";
            String className = "类名";
            // 解析jar 传入jar文件路径
            Class<?> clazz = getClassesFromJar(fileId, className);
            if (clazz == null) {
                log.error("jar包中类名不匹配!");
                return R.error().message("jar包中类名不匹配!");
            }
            // 如果不是静态方法创建新的对象
            //Object ob = clazz.newInstance();

            // 获取方法
            Method method = clazz.getMethod(methodName, String.class, String.class);
            if (method == null) {
                log.error("jar包中方法名不匹配!");
                return R.error().message("jar包中方法名不匹配!");
            }
            if (method.getParameterTypes().length == 0) {
                log.error("解析方法参数为空,检查jar包" + methodName + "方法缺少参数");
                return R.error().message("解析方法参数为空,检查jar包" + methodName + "方法缺少参数");
            }

            // 执行方法,解析数据
            Map<String, Object> result = (Map<String, Object>) method.invoke(clazz, deviceType, data);
            log.info("解析完成,接收到的返回数据:" + result);
/**
     * 解析jar包中所有的类
     *
     * @param jarPath jar 路径
     * @return
     * @throws Exception
     */
    public static Class<?> getClassesFromJar(String jarPath, String className) {
        // 获取项目所在路径
        String newPath = System.getProperty("user.dir");

        // 输入流
        InputStream newInput = null;
        // 输出流
        OutputStream newOutput = null;

        // 存储加载的类
        Class<?> myclass = null;
        // 加载jar包
        JarFile jarFile = null;

        // 类加载器
        URLClassLoader myClassLoader = null;
        try {
            // 创建文件存储路径
            String fileName = jarPath.substring(jarPath.lastIndexOf("/") + 1);
            newPath = newPath + "\\dataAnalFile\\" + fileName;
            File newFile = new File(newPath);
            // 不存在则创建路径
            if (!newFile.getParentFile().exists()) {
                newFile.getParentFile().mkdirs();
            }

            // 判断文件是否存在,如果不存在根据地址下载直接获取。否则直接通过路径获取
            if (!newFile.exists()) {
                // 根据文件地址下载文件到新路径
                URL downUrl = new URL(jarPath);
                // 打开连接
                HttpURLConnection connection = (HttpURLConnection) downUrl.openConnection();
                int code = connection.getResponseCode();
                if (code == 200) {
                    newInput = connection.getInputStream();
                    newOutput = new FileOutputStream(newFile);

                    byte[] bytes = new byte[2048];
                    int bytesRead;
                    // 写入数据
                    while ((bytesRead = newInput.read(bytes)) != -1) {
                        newOutput.write(bytes, 0, bytesRead);
                    }
                }
            }

            // 获取从新的文件存储地址文件
            File file = new File(newPath);
            URL url = file.toURI().toURL();
            // 创建类加载器
            myClassLoader = new URLClassLoader(new URL[]{url}, Thread.currentThread().getContextClassLoader());
            // 加载jar包文件
            jarFile = new JarFile(file);

            // 遍历jar包中的所有文件
            Enumeration<JarEntry> es = jarFile.entries();
            while (es.hasMoreElements()) {
                JarEntry e = es.nextElement();
                String name = e.getName();

                if (name.endsWith(".class")) {
                    // 获取类名
                    if (name.substring(name.lastIndexOf("/"), name.length()).contains(className)) {
                        // 获取指定类名
                        String nameStr = name.substring(0, name.length() - 6).replace('/', '.');
                        myclass = myClassLoader.loadClass(nameStr);
                        jarFile.close();
                        myClassLoader.close();
                        return myclass;
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (newInput != null) {
                    newInput.close();
                }
                if (newOutput != null) {
                    newOutput.close();
                }
                if (jarFile != null) {
                    jarFile.close();
                }
                if (myClassLoader != null) {
                    myClassLoader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return myclass;
    }

 方式二:通过路径下载到本地,并解析jar包

/**
     * 解析jar包中所有的类
     * @param jarPath jar 路径
     * @return
     * @throws Exception
     */
    public static Class<?> getClassesFromJar(String jarPath,String className) throws Exception {
        // 获取文件
        File file = new File(jarPath);
        URL url = file.toURI().toURL();
        URLClassLoader myClassLoader = new URLClassLoader(new URL[]{url}, Thread.currentThread().getContextClassLoader());
        JarFile jarFile = new JarFile(file);

        Enumeration<JarEntry> es = jarFile.entries();
        Class<?> myclass=null;
        while (es.hasMoreElements()) {
            JarEntry e = es.nextElement();
            String name = e.getName();

            if (name.endsWith(".class")) {
                if (name.substring(name.lastIndexOf("/"),name.length()).contains(className)){
                    // 获取指定类名
                    String nameStr = name.substring(0, name.length() - 6).replace('/', '.');
                    myclass = myClassLoader.loadClass(nameStr);
                    jarFile.close();
                    return myclass;
                }
            }
        }
        jarFile.close();
        return myclass;
    }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值