waylonion
waylonion

Reputation: 6976

Extract class names from JAR with special formatting

How would I extract all the available classes from a Jar file and dump the output, after some simple processing, to a txt file.

For example, if I run jar tf commons-math3-3.1.6.jar a subset of the output would be:

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

I would like to convert all / to .

And all $ to .

Finally I would also like to remove the .class that appears at the end of every string.

For instance:

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

would become

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

Upvotes: 1

Views: 366

Answers (2)

Cristofor
Cristofor

Reputation: 2097

Executing shell commands in programs isn't very nice in my opinion so what you can do is to inspect the file programmatically.

Take this example, we'll fill classNames with the list of all Java classes contained inside a jar file at /path/to/jar/file.jar.

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('$', '.');
        classNames.add(className.substring(0, className.length() - ".class".length()));
    }
}

Credit: Here

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522032

String path = "org/apache/commons/math3/analysis/integration/gauss/BaseRuleFactory.class";
path = path.replaceAll("/", ".")
           .replaceAll("\\$(\\d+)\\.class", "\\.$1");

Upvotes: 1

Related Questions