150

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.

Roman C
  • 49,761
  • 33
  • 66
  • 176
sticksu
  • 3,660
  • 3
  • 23
  • 41
  • Are you using some IDE?As it will be auto displayed if you are using one. – joey rohan Mar 30 '13 at 16:33
  • I am using Eclipse, but I need to do this with code. – sticksu Mar 30 '13 at 16:34
  • @LuiggiMendoza - The potential duplicate has answers with examples as well as resources for documentation. Searching for one of those class names + example will yield several useful results. – Aiias Mar 30 '13 at 16:41
  • @Alias the possible duplicate states how to find and get a file from a jar, while the question is about getting the class names inside a jar (possibly the classes in all packages inside it). The link in ErikKaju's answer points to a possible solution using `JarInputStream` and `JarEntry` classes that I can't find in any answer of your referred link. – Luiggi Mendoza Mar 30 '13 at 16:58

13 Answers13

251

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

Philip Rego
  • 552
  • 4
  • 20
  • 35
Sanjeev Gupta
  • 2,519
  • 2
  • 11
  • 2
  • 5
    Thanks. This answers the "just get a class listing" part of the OP that wasn't asked. – octopusgrabbus Nov 09 '13 at 17:58
  • 16
    You can also use `unzip -l jarfile.jar` in a pinch. A JAR file is just a zip file with a manifest! – sigpwned May 19 '15 at 12:45
  • 4
    The issue is that he likely wanted to get the class files inside a jar at runtime, given a classloader instance (likely to see what classes are loaded inside that specific jar). – Richard Duerr Jul 07 '16 at 20:56
  • This is great! And I found the office doc here. https://docs.oracle.com/javase/tutorial/deployment/jar/view.html – Zihao Zhao Sep 17 '20 at 16:53
  • Also, this won't allow you to inspect annotations, which is likely something you'll want to do if you're scanning classes at runtime. – searchengine27 Aug 16 '21 at 20:11
78

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);
sigpwned
  • 6,957
  • 5
  • 28
  • 48
20

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
prayagupa
  • 30,204
  • 14
  • 155
  • 192
13

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.

stanm
  • 3,201
  • 1
  • 27
  • 36
8

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

GreenAsJade
  • 14,459
  • 11
  • 63
  • 98
Pallav
  • 99
  • 1
  • 1
7

You can use the

jar tf example.jar
loneStar
  • 3,780
  • 23
  • 40
4

Below command will list the content of a jar file.

command :- unzip -l jarfilename.jar.

sample o/p :-

Archive: hello-world.jar 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 (^).

Amit
  • 30,756
  • 6
  • 57
  • 88
  • Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) of *how* and *why* this solves the problem. Remember that you are answering the question for readers in the future, not just the person asking now! Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Feb 21 '17 at 11:56
4

Mac OS: On Terminal:

vim <your jar location>

after jar gets opened, press / and pass your class name and hit enter
Rajiv Singh
  • 958
  • 1
  • 9
  • 14
2

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

2

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 "/", ".")
    }
}
0

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

Udayraj Deshmukh
  • 1,814
  • 1
  • 14
  • 22
0

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")
Vikas
  • 41
  • 5
0

Today I started working on this basic problem, the problem is that I needed to look at a package path for java enumerations and create a list of instances implementing a specific interface. The package was in a jar file dependency as part of a spring boot application.

The first problem, getting a list of classes from the jar file. spring boot made that fairly simple once I found the solution.

ClassLoader classLoader = this.getClass().getClassLoader();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(classLoader);
Resource[] resources = new Resource[0];
try {
    resources = resolver.getResources("classpath:com/enumeration/*.class");
} catch (IOException e) {
    LOGGER.error("failed to load Enumeration classes using classpath: >{}< {}", "classpath:com/enumeration/*.class", e.toString());
}   

Once I found the list of classes, instantiating the enumerations worked with the following code. This is outside the scope of the initial question but exemplifies traversing a list of class files in a package.

List<Enum> list = new ArrayList<>();
for (Resource resource : resources) {
    String classPathName = ((ClassPathResource) resource).getPath().replaceAll("/", ".").replaceAll(".class", "");
    Class<?> aClass = Class.forName(classPathName);
    Class<Enum> aClass1 = (Class<Enum>) aClass;
    Enum anEnum = Enum.valueOf(aClass1, aClass1.getEnumConstants()[0].name());
    list.add(anEnum);
}
Dan F
  • 31
  • 4