Reputation: 3738
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.
Upvotes: 158
Views: 220530
Reputation: 61
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);
}
Upvotes: 1
Reputation: 1088
Mac OS: On Terminal:
vim <your jar location>
after jar gets opened, press / and pass your class name and hit enter
Upvotes: 4
Reputation: 41
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 "/", ".")
}
}
Upvotes: 4
Reputation: 41
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")
Upvotes: 0
Reputation: 2639
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
Upvotes: 263
Reputation: 1
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:
Create a sample Eclipse Java project.
All all the jars you have in its Build Path
CTRL+SHIFT+T and Type the full class name .
Results will be displayed in the window with all the jars having that class. See attached picture .
Upvotes: 0
Reputation: 32386
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 (^).
Upvotes: 4
Reputation: 3321
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.
Upvotes: 13
Reputation: 7453
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.
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()));
}
}
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...
}
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);
Upvotes: 81
Reputation: 29
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
Upvotes: 2
Reputation: 31262
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 .class
es 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 class
es,
jar tvf launcher/target/usergrid-launcher-1.0-SNAPSHOT.jar | grep .class | wc -l
61079
Upvotes: 21
Reputation: 99
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
Upvotes: 8