How to get names of classes inside a jar file?

JavaFileClassJarClassloader

Java Problem Overview


I have a JAR file and I need to get the name of all classes inside this JAR file. How can I do that?

I googled it and saw something about JarFile or Java ClassLoader but I have no idea how to do it.

Java Solutions


Solution 1 - Java

You can use Java jar tool. List the content of jar file in a txt file and you can see all the classes in the jar.

jar tvf jarfile.jar

> -t list table of contents for archive

> -v generate verbose output on standard output

> -f specify archive file name

Solution 2 - Java

Unfortunately, Java doesn't provide an easy way to list classes in the "native" JRE. That leaves you with a couple of options: (a) for any given JAR file, you can list the entries inside that JAR file, find the .class files, and then determine which Java class each .class file represents; or (b) you can use a library that does this for you.

Option (a): Scanning JAR files manually

In this option, 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('/', '.'); // including ".class"
        classNames.add(className.substring(0, className.length() - ".class".length()));
    }
}

Option (b): Using specialized reflections libraries

Guava

Guava has had ClassPath since at least 14.0, which I have used and liked. One nice thing about ClassPath is that it doesn't load the classes it finds, which is important when you're scanning for a large number of classes.

ClassPath cp=ClassPath.from(Thread.currentThread().getContextClassLoader());
for(ClassPath.ClassInfo info : cp.getTopLevelClassesRecurusive("my.package.name")) {
    // Do stuff with classes here...
}
Reflections

I haven't personally used the Reflections library, but it seems well-liked. Some great examples are provided on the website like this quick way to load all the classes in a package provided by any JAR file, which may also be useful for your application.

Reflections reflections = new Reflections("my.project.prefix");

Set<Class<? extends SomeType>> subTypes = reflections.getSubTypesOf(SomeType.class);

Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(SomeAnnotation.class);

Solution 3 - Java

Maybe you are looking for jar command to get the list of classes in terminal,

$ jar tf ~/.m2/repository/org/apache/spark/spark-assembly/1.2.0-SNAPSHOT/spark-assembly-1.2.0-SNAPSHOT-hadoop1.0.4.jar 
META-INF/
META-INF/MANIFEST.MF
org/
org/apache/
org/apache/spark/
org/apache/spark/unused/
org/apache/spark/unused/UnusedStubClass.class
META-INF/maven/
META-INF/maven/org.spark-project.spark/
META-INF/maven/org.spark-project.spark/unused/
META-INF/maven/org.spark-project.spark/unused/pom.xml
META-INF/maven/org.spark-project.spark/unused/pom.properties
META-INF/NOTICE

where,

-t  list table of contents for archive
-f  specify archive file name

Or, just grep above result to see .classes only

$ jar tf ~/.m2/repository/org/apache/spark/spark-assembly/1.2.0-SNAPSHOT/spark-assembly-1.2.0-SNAPSHOT-hadoop1.0.4.jar | grep .class
org/apache/spark/unused/UnusedStubClass.class

To see number of classes,

jar tvf launcher/target/usergrid-launcher-1.0-SNAPSHOT.jar | grep .class | wc -l
61079

Solution 4 - Java

This is a hack I'm using:

You can use java's autocomplete like this:

java -cp path_to.jar <Tab>

This will give you a list of classes available to pass as the starting class. Of course, trying to use one that has no main file will not do anything, but you can see what java thinks the classes inside the .jar are called.

Solution 5 - Java

You can try:

jar tvf jarfile.jar 

This will be helpful only if your jar is executable i.e. in manifest you have defined some class as main class

Solution 6 - Java

You can use the

jar tf example.jar

Solution 7 - Java

Below command will list the content of a jar file.

command :- unzip -l jarfilename.jar.

sample o/p :-

  Length      Date    Time    Name
---------  ---------- -----   ----
     43161  10-18-2017 15:44   hello-world/com/ami/so/search/So.class
     20531  10-18-2017 15:44   hello-world/com/ami/so/util/SoUtil.class
---------                     -------
    63692                     2 files```


According to manual of `unzip` 

> -l     list archive files (short format).  The names, uncompressed file sizes and modification dates and times of the specified files are
> printed, along with totals  for  all
>               files  specified.   If UnZip was compiled with OS2_EAS defined, the -l option also lists columns for the sizes of stored OS/2
> extended attributes (EAs) and OS/2 access
>               control lists (ACLs).  In addition, the zipfile comment and individual file comments (if any) are displayed.  If a file was
> archived from  a  single-case  file  system
>               (for example, the old MS-DOS FAT file system) and the -L option was given, the filename is converted to lowercase and is
> prefixed with a caret (^).

Solution 8 - Java

Mac OS: On Terminal:

vim <your jar location>

after jar gets opened, press / and pass your class name and hit enter

Solution 9 - Java

You can try this :

unzip -v /your/jar.jar

This will be helpful only if your jar is executable i.e. in manifest you have defined some class as main class

Solution 10 - Java

Use this bash script:

#!/bin/bash

for VARIABLE in *.jar
do
   jar -tf $VARIABLE |grep "\.class"|awk -v arch=$VARIABLE '{print arch ":" $4}'|sed 's/\//./g'|sed 's/\.\.//g'|sed 's/\.class//g'
done

this will list the classes inside jars in your directory in the form:

file1.jar:fullyqualifiedclassName
file1.jar:fullyqualifiedclassName
file1.jar:fullyqualifiedclassName
file1.jar:fullyqualifiedclassName
file2.jar:fullyqualifiedclassName
file2.jar:fullyqualifiedclassName
file2.jar:fullyqualifiedclassName

Sample output:

commons-io.jar:org.apache.commons.io.ByteOrderMark
commons-io.jar:org.apache.commons.io.Charsets
commons-io.jar:org.apache.commons.io.comparator.AbstractFileComparator
commons-io.jar:org.apache.commons.io.comparator.CompositeFileComparator
commons-io.jar:org.apache.commons.io.comparator.DefaultFileComparator
commons-io.jar:org.apache.commons.io.comparator.DirectoryFileComparator
commons-io.jar:org.apache.commons.io.comparator.ExtensionFileComparator
commons-io.jar:org.apache.commons.io.comparator.LastModifiedFileComparator

In windows you can use powershell:

Get-ChildItem -File -Filter *.jar |
ForEach-Object{
    $filename = $_.Name
    Write-Host $filename
    $classes = jar -tf $_.Name |Select-String -Pattern '.class' -CaseSensitive -SimpleMatch
    ForEach($line in $classes) {
       write-host $filename":"(($line -replace "\.class", "") -replace "/", ".")
    }
}

Solution 11 - Java

Description OF Solution : Eclipse IDE can be used for this by creating a sample java project and add all jars in the Project Build path

STEPS below:

  1. Create a sample Eclipse Java project.

  2. All all the jars you have in its Build Path

  3. CTRL+SHIFT+T and Type the full class name .

  4. Results will be displayed in the window with all the jars having that class. See attached picture . enter image description here

Solution 12 - Java

windows cmd: This would work if you have all te jars in the same directory and execute the below command

for /r %i in (*) do ( jar tvf %i | find /I "search_string")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsticksuView Question on Stackoverflow
Solution 1 - JavaSanjeev GuptaView Answer on Stackoverflow
Solution 2 - JavasigpwnedView Answer on Stackoverflow
Solution 3 - JavaprayagupaView Answer on Stackoverflow
Solution 4 - JavastanmView Answer on Stackoverflow
Solution 5 - JavaPallavView Answer on Stackoverflow
Solution 6 - JavaloneStarView Answer on Stackoverflow
Solution 7 - JavaAmitView Answer on Stackoverflow
Solution 8 - JavaRajiv SinghView Answer on Stackoverflow
Solution 9 - JavaAbhimanyu DuttaView Answer on Stackoverflow
Solution 10 - JavaESPRIELLA_GREGORIO QUINTERO_DEView Answer on Stackoverflow
Solution 11 - JavaArokiadoss AsirvathamView Answer on Stackoverflow
Solution 12 - JavaVikas View Answer on Stackoverflow