【问题标题】:Extract class names from JAR with special formatting从具有特殊格式的 JAR 中提取类名
【发布时间】:2017-02-24 23:18:28
【问题描述】:

如何从 Jar 文件中提取所有可用的类,并在经过一些简单处理后将输出转储到 txt 文件中。

例如,如果我运行jar tf commons-math3-3.1.6.jar,输出的一个子集将是:

org/apache/commons/math3/analysis/differentiation/UnivariateVectorFunctionDifferentiator.class
org/apache/commons/math3/analysis/differentiation/FiniteDifferencesDifferentiator$2.class
org/apache/commons/math3/analysis/differentiation/SparseGradient$1.class
org/apache/commons/math3/analysis/integration/IterativeLegendreGaussIntegrator$1.class
org/apache/commons/math3/analysis/integration/gauss/LegendreHighPrecisionRuleFactory.class
org/apache/commons/math3/analysis/integration/gauss/BaseRuleFactory.class
org/apache/commons/math3/analysis/integration/gauss/HermiteRuleFactory.class
org/apache/commons/math3/analysis/integration/gauss/LegendreRuleFactory.class
org/apache/commons/math3/analysis/integration/gauss/GaussIntegratorFactory.class

我想将所有 / 转换为 。

以及所有 $ 到 。

最后我还想删除出现在每个字符串末尾的 .class。

例如:

org/apache/commons/math3/analysis/differentiation/FiniteDifferencesDifferentiator$2.class

会变成

org.apache.commons.math3.analysis.differentiation.FiniteDifferencesDifferentiator.2

【问题讨论】:

    标签: java regex linux shell jar


    【解决方案1】:
    String path = "org/apache/commons/math3/analysis/integration/gauss/BaseRuleFactory.class";
    path = path.replaceAll("/", ".")
               .replaceAll("\\$(\\d+)\\.class", "\\.$1");
    

    【讨论】:

      【解决方案2】:

      在我看来,在程序中执行 shell 命令不是很好,所以你可以做的是以编程方式检查文件。

      以这个例子为例,我们将使用包含在/path/to/jar/file.jar. 的 jar 文件中的所有 Java 类的列表填充 classNames

      List<String> classNames = new ArrayList<String>();
      ZipInputStream zip = new ZipInputStream(new FileInputStream("/path/to/jar/file.jar"));
      for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
          if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
              // This ZipEntry represents a class. Now, what class does it represent?
              String className = entry.getName().replace('/', '.').replace('$',''); // including ".class"
              classNames.add(className.substring(0, className.length() - ".class".length()));
          }
      }
      

      信用:Here

      【讨论】:

        猜你喜欢
        • 2011-05-02
        • 1970-01-01
        • 2021-04-04
        • 2021-12-05
        • 2020-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-28
        相关资源
        最近更新 更多