根据关键字查找xxx-sources.jar中的文件

阅读:363
作者:majingjing
发布:2019-10-09 09:45:22

我们在编写代码时经常会遇到知道某个参数键,但是却不知道这个参数是在哪里被赋值的?
问题场景 https://github.com/majinding/webservice/issues/10
开发工具也无法搜索到jar包中的内容.(目前我不知道如何查找,如果有更好的查找方式,请告诉我)

示例: 比如我要查找 有一个header中填充了 “jaxrs.template.parameters”这个参数值,我想知道这个值是在哪里进行set的?

根据关键字查找在xxx-sources.jar中的文件

实现方式: 将jar文件(源代码)加载到内存中,再进行字符匹配查找

    /**
     * 在jar文件中搜索内容(仅限xxx-sources.jar)
     *
     * @param jfInst       jar文件
     * @param searchString 搜索内容
     */
    public static void searchContent(JarFile jfInst, String searchString) {
        Enumeration enumEntry = jfInst.entries();
        while (enumEntry.hasMoreElements()) {
            JarEntry jarEntry = (JarEntry) enumEntry.nextElement();

            try {
                InputStream ins = jfInst.getInputStream(jarEntry);
                BufferedReader br = new BufferedReader(new InputStreamReader(ins));
                String line;
                int lineNumber = 0;
                while ((line = br.readLine()) != null) {
                    ++lineNumber;
                    if (line.contains(searchString)) {
                        System.out.println(jarEntry + "\t" + lineNumber);
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

使用方式: 指定xxx-sources.jar文件,和查找关键字

    @Test
    public void search() throws IOException {
        JarFile jarFile = new JarFile("/maven/repos/org/apache/cxf/cxf-rt-frontend-jaxrs/3.1.3/cxf-rt-frontend-jaxrs-3.1.3-sources.jar");
        Decompression.searchContent(jarFile,"jaxrs.template.parameters");
    }

查找结果如下: 路径+行号