Java get all class in jar

Viewing the Contents of a JAR File

The basic format of the command for viewing the contents of a JAR file is:

Let’s look at the options and argument used in this command:

  • The t option indicates that you want to view the table of contents of the JAR file.
  • The f option indicates that the JAR file whose contents are to be viewed is specified on the command line.
  • The jar-file argument is the path and name of the JAR file whose contents you want to view.

The t and f options can appear in either order, but there must not be any space between them.

This command will display the JAR file’s table of contents to stdout.

You can optionally add the verbose option, v, to produce additional information about file sizes and last-modified dates in the output.

An Example

Let’s use the Jar tool to list the contents of the TicTacToe.jar file we created in the previous section:

Читайте также:  Python listing all files in directory

This command displays the contents of the JAR file to stdout:

META-INF/MANIFEST.MF TicTacToe.class audio/ audio/beep.au audio/ding.au audio/return.au audio/yahoo1.au audio/yahoo2.au images/ images/cross.gif images/not.gif

The JAR file contains the TicTacToe class file and the audio and images directory, as expected. The output also shows that the JAR file contains a default manifest file, META-INF/MANIFEST.MF, which was automatically placed in the archive by the JAR tool. For more information, see the Understanding the Default Manifest section.

All pathnames are displayed with forward slashes, regardless of the platform or operating system you’re using. Paths in JAR files are always relative; you’ll never see a path beginning with C:, for example.

The JAR tool will display additional information if you use the v option:

For example, the verbose output for the TicTacToe JAR file would look similar to this:

68 Thu Nov 01 20:00:40 PDT 2012 META-INF/MANIFEST.MF 553 Mon Sep 24 21:57:48 PDT 2012 TicTacToe.class 3708 Mon Sep 24 21:57:48 PDT 2012 TicTacToe.class 9584 Mon Sep 24 21:57:48 PDT 2012 TicTacToe.java 0 Mon Sep 24 21:57:48 PDT 2012 audio/ 4032 Mon Sep 24 21:57:48 PDT 2012 audio/beep.au 2566 Mon Sep 24 21:57:48 PDT 2012 audio/ding.au 6558 Mon Sep 24 21:57:48 PDT 2012 audio/return.au 7834 Mon Sep 24 21:57:48 PDT 2012 audio/yahoo1.au 7463 Mon Sep 24 21:57:48 PDT 2012 audio/yahoo2.au 424 Mon Sep 24 21:57:48 PDT 2012 example1.html 0 Mon Sep 24 21:57:48 PDT 2012 images/ 157 Mon Sep 24 21:57:48 PDT 2012 images/cross.gif 158 Mon Sep 24 21:57:48 PDT 2012 images/not.gif

Источник

In Java How to Find List of all Class Names from inside .jar File? – Jar Class Finder Utility with Java Reflection

This tutorial will be very interesting. Last week I was working on a Java Project which requires me to have list of Classes from .jar file. With the help of JarEntry and JarInputStream utility I was able to extract all classes from inside of .jar file.

JarInputStream creates a new JarInputStream and reads the optional manifest. If a manifest is present, also attempts to verify the signatures if the JarInputStream is signed.

Below solution will also work for your if you have any of below query:

  • In Java – How to find a class somewhere inside dozens of JAR files
  • How to get names of classes inside a jar file?
  • Looking for a Java class in a set of JARs with find

how-to-find-list-of-all-class-names-from-inside-jar-file

Let’s get started. We will perform below steps.

  1. Create class CrunchifyFindClassesFromJar.java
  2. Create utility method called getCrunchifyClassNamesFromJar(String jarFileName)
  3. Iterate through nextJarEntry and if found remove .class from name add it to JSON list
  4. Print JSONObject containing above class list
package com.crunchify.tutorial; import java.io.FileInputStream; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; import org.json.JSONArray; import org.json.JSONObject; /** * @author Crunchify.com * */ public class CrunchifyFindClassesFromJar < @SuppressWarnings("resource") public static JSONObject getCrunchifyClassNamesFromJar(String crunchifyJarName) < JSONArray listofClasses = new JSONArray(); JSONObject crunchifyObject = new JSONObject(); try < JarInputStream crunchifyJarFile = new JarInputStream(new FileInputStream(crunchifyJarName)); JarEntry crunchifyJar; while (true) < crunchifyJar = crunchifyJarFile.getNextJarEntry(); if (crunchifyJar == null) < break; >if ((crunchifyJar.getName().endsWith(".class"))) < String className = crunchifyJar.getName().replaceAll("/", "\\."); String myClass = className.substring(0, className.lastIndexOf('.')); listofClasses.put(myClass); >> crunchifyObject.put("Jar File Name", crunchifyJarName); crunchifyObject.put("List of Class", listofClasses); > catch (Exception e) < System.out.println("Oops.. Encounter an issue while parsing jar" + e.toString()); >return crunchifyObject; > public static void main(String[] args) < JSONObject myList = getCrunchifyClassNamesFromJar("/Users//Documents/javax.servlet.jsp.jar"); System.out.println(myList); > >
< "List of Class": [ "javax.el.ArrayELResolver", "javax.el.BeanELResolver$BeanProperties", "javax.el.BeanELResolver$BeanProperty", "javax.el.BeanELResolver", "javax.el.CompositeELResolver$CompositeIterator", "javax.el.CompositeELResolver", "javax.el.ELContext", "javax.el.ELContextEvent", . . so many more. ], "Jar File Name": "/Users//Documents/javax.servlet.jsp.jar" >

Bonus point:

Check out how to find if particular jar contains specific method.

try < ClasscrunchifyClass = Class.forName(className); Method main = crunchifyClass.getDeclaredMethod("yourMethodName"); main.invoke(null); > catch (Exception e)

Hope this mini utility will help if you want to quickly achieve the same goal. Feel free to use it in your production project.

If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.

Suggested Articles.

Источник

Java get all class in jar

  • Language
  • HTML & CSS
  • Form
  • Java interaction
  • Mobile
  • Varia
  • Language
  • String / Number
  • AWT
  • Swing
  • Environment
  • IO
  • JS interaction
  • JDBC
  • Thread
  • Networking
  • JSP / Servlet
  • XML / RSS / JSON
  • Localization
  • Security
  • JNI / JNA
  • Date / Time
  • Open Source
  • Varia
  • Powerscript
  • Win API & Registry
  • Datawindow
  • PFC
  • Common problems
  • Database
  • WSH & VBScript
  • Windows, Batch, PDF, Internet
  • BigIndex
  • Download
  • TS2068, Sinclair QL Archives
  • Real’s HowTo FAQ
  • Donate!
  • Funny 1
  • Funny 2
  • Funny 3
  • Funny 4
  • One line
  • Ascii Art
  • Deprecated (old stuff)

    Get list of classes in package (in a Jar) Tag(s): Environment

    About cookies on this site

    We use cookies to collect and analyze information on site performance and usage, to provide social media features and to enhance and customize content and advertisements.

    import java.util.jar.*; import java.util.*; import java.io.*; public class PackageUtils < private static boolean debug = true; private PackageUtils() <>public static List getClasseNamesInPackage (String jarName, String packageName) < ArrayList classes = new ArrayList (); packageName = packageName.replaceAll("\\." , "/"); if (debug) System.out.println ("Jar " + jarName + " looking for " + packageName); try< JarInputStream jarFile = new JarInputStream (new FileInputStream (jarName)); JarEntry jarEntry; while(true) < jarEntry=jarFile.getNextJarEntry (); if(jarEntry == null)< break; >if((jarEntry.getName ().startsWith (packageName)) && (jarEntry.getName ().endsWith (".class")) ) < if (debug) System.out.println ("Found " + jarEntry.getName().replaceAll("/", "\\.")); classes.add (jarEntry.getName().replaceAll("/", "\\.")); >> > catch( Exception e) < e.printStackTrace (); >return classes; > /** * */ public static void main (String[] args) < List list = PackageUtils.getClasseNamesInPackage ("C:/j2sdk1.4.1_02/lib/mail.jar", "com.sun.mail.handlers"); System.out.println(list); /* output : Jar C:/j2sdk1.4.1_02/lib/mail.jar looking for com/sun/mail/handlers Found com.sun.mail.handlers.text_html.class Found com.sun.mail.handlers.text_plain.class Found com.sun.mail.handlers.text_xml.class Found com.sun.mail.handlers.image_gif.class Found com.sun.mail.handlers.image_jpeg.class Found com.sun.mail.handlers.multipart_mixed.class Found com.sun.mail.handlers.message_rfc822.class [com.sun.mail.handlers.text_html.class, com.sun.mail.handlers.text_xml.class, com .sun.mail.handlers.image_jpeg.class, , com.sun.mail.handlers.message_rfc822.class] */ >>

    Источник

    Получить имена классов внутри файла JAR

    Узнайте, как получить имена классов внутри данного JAR-файла и как загрузить классы из JAR-файла во время выполнения.

    1. Обзор

    Большинство библиотек Java доступны в виде JAR-файлов . В этом уроке мы рассмотрим, как получить имена классов внутри данного JAR-файла из командной строки и из программы Java.

    Затем мы рассмотрим пример Java-программы, загружающей классы из данного JAR-файла во время выполнения.

    2. Пример JAR-файла

    В этом уроке мы возьмем stripe-0.0.1-SNAPSHOT.jar файл в качестве примера для решения вопроса о том, как получить имена классов в JAR-файле:

    3. Использование команды jar

    JDK поставляется с командой jar . Мы можем использовать эту команду с опциями t и f для перечисления содержимого файла JAR :

    $ jar tf stripe-0.0.1-SNAPSHOT.jar META-INF/ META-INF/MANIFEST.MF . templates/result.html templates/checkout.html application.properties com/baeldung/stripe/StripeApplication.class com/baeldung/stripe/ChargeRequest.class com/baeldung/stripe/StripeService.class com/baeldung/stripe/ChargeRequest$Currency.class .

    Поскольку нас интересуют только файлы *.class в архиве, мы можем отфильтровать выходные данные с помощью команды grep :

    $ jar tf stripe-0.0.1-SNAPSHOT.jar | grep '\.class$' com/baeldung/stripe/StripeApplication.class com/baeldung/stripe/ChargeRequest.class com/baeldung/stripe/StripeService.class com/baeldung/stripe/ChargeRequest$Currency.class com/baeldung/stripe/ChargeController.class com/baeldung/stripe/CheckoutController.class

    Это дает нам список файлов классов внутри файла JAR.

    4. Получение имен классов JAR – файла в Java

    Использование команды jar для печати имен классов из файла JAR довольно просто. Однако иногда мы хотим загрузить некоторые классы из JAR-файла в нашу Java-программу. В этом случае вывода командной строки недостаточно.

    Для достижения нашей цели нам нужно отсканировать JAR – файл из Java – программы и получить имена классов.

    Давайте посмотрим, как извлечь имена классов из нашего примера JAR-файла с помощью Jar-файла и JarEntry классов :

    public static Set getClassNamesFromJarFile(File givenFile) throws IOException < SetclassNames = new HashSet<>(); try (JarFile jarFile = new JarFile(givenFile)) < Enumeratione = jarFile.entries(); while (e.hasMoreElements()) < JarEntry jarEntry = e.nextElement(); if (jarEntry.getName().endsWith(".class")) < String className = jarEntry.getName() .replace("/", ".") .replace(".class", ""); classNames.add(className); >> return classNames; > > 

    Теперь давайте подробнее рассмотрим код в приведенном выше методе и поймем, как он работает:

    • try (JarFile JarFile(givenFile)) – Здесь мы использовали оператор try-with-resources для получения jarFile из данного Файла объекта
    • if (JarEntry.getName().EndsWith(“.class”)) – Мы берем каждый класс JarEntry и меняем путь файла класса на квалифицированное имя класса, например change “package1/package2/SomeType.class” into “package1.package2.SomeType”

    Давайте проверим, может ли этот метод извлечь имена классов из нашего примера JAR-файла с помощью метода модульного тестирования:

    private static final String JAR_PATH = "example-jar/stripe-0.0.1-SNAPSHOT.jar"; private static final Set EXPECTED_CLASS_NAMES = Sets.newHashSet( "com.baeldung.stripe.StripeApplication", "com.baeldung.stripe.ChargeRequest", "com.baeldung.stripe.StripeService", "com.baeldung.stripe.ChargeRequest$Currency", "com.baeldung.stripe.ChargeController", "com.baeldung.stripe.CheckoutController"); @Test public void givenJarFilePath_whenLoadClassNames_thenGetClassNames() throws IOException, URISyntaxException < File jarFile = new File( Objects.requireNonNull(getClass().getClassLoader().getResource(JAR_PATH)).toURI()); SetclassNames = GetClassNamesFromJar.getClassNamesFromJarFile(jarFile); Assert.assertEquals(EXPECTED_CLASS_NAMES, classNames); > 

    5. Получение классов из JAR-файла в Java

    Мы видели, как получить имена классов из файла JAR. Иногда мы хотим динамически загружать некоторые классы из JAR-файла во время выполнения.

    В этом случае мы можем сначала получить имена классов из данного JAR-файла с помощью нашего метода getClassNamesFromJarFile .

    Далее мы можем создать ClassLoader для загрузки необходимых классов по имени:

    public static Set getClassesFromJarFile(File jarFile) throws IOException, ClassNotFoundException < SetclassNames = getClassNamesFromJarFile(jarFile); Set classes = new HashSet<>(classNames.size()); try (URLClassLoader cl = URLClassLoader.newInstance( new URL[] < new URL("jar:file:" + jarFile + "!/") >)) < for (String name : classNames) < Class clazz = cl.loadClass(name); // Load the class by its name classes.add(clazz); >> return classes; >

    В приведенном выше методе мы создали объект URLClassLoader для загрузки классов. Реализация довольно проста.

    Однако, вероятно, стоит немного объяснить синтаксис URL-адреса JAR. Допустимый URL-адрес JAR содержит три части: “ jar: + [расположение файла JAR] + !/”.

    Окончание “ !/ ” указывает на то, что URL-адрес JAR ссылается на весь файл JAR. Давайте посмотрим несколько примеров URL-адресов JAR:

    jar:http://www.example.com/some_jar_file.jar!/ jar:file:/local/path/to/some_jar_file.jar!/ jar:file:/C:/windows/path/to/some_jar_file.jar!/

    В нашем методе get Classes From Jar File файл JAR находится в локальной файловой системе, поэтому префикс URL-адреса равен ” file: “.

    Теперь давайте напишем тестовый метод, чтобы проверить, может ли наш метод получить все ожидаемые объекты Class :

    @Test public void givenJarFilePath_whenLoadClass_thenGetClassObjects() throws IOException, ClassNotFoundException, URISyntaxException < File jarFile = new File(Objects.requireNonNull(getClass().getClassLoader().getResource(JAR_PATH)).toURI()); Setclasses = GetClassNamesFromJar.getClassesFromJarFile(jarFile); Set names = classes.stream().map(Class::getName).collect(Collectors.toSet()); Assert.assertEquals(EXPECTED_CLASS_NAMES, names); > 

    Как только у нас есть необходимые объекты Class , мы можем использовать Java reflection для создания экземпляров классов и вызова методов.

    6. Заключение

    В этой статье мы изучили два различных подхода к получению имен классов из данного JAR-файла.

    Команда jar может печатать имена классов. Это довольно удобно, если нам нужно проверить, содержит ли файл JAR данный класс. Однако, если нам нужно получить имена классов из запущенной Java-программы, Jar File и JarEntry могут помочь нам достичь этого.

    Наконец, мы также видели пример Java-программы для загрузки классов из JAR-файла во время выполнения.

    Как всегда, полный исходный код статьи доступен на GitHub .

    Читайте ещё по теме:

    Источник

Оцените статью