2016-12-26 2 views
0

У меня есть Jar в java, который содержит 2 класса и 1 интерфейс. Как я могу получить интерфейс и имена классов из банки. В настоящее время я могу получить имена классов, но не имя интерфейса.Как напечатать имя класса и интерфейса из файла java jar

List jClasses = getClasseNames("D://Test.jar"); 

      System.out.println(jClasses.size()); 

      for (int i = 0; i < jClasses.size(); i++) { 

       System.out.println("Print Classes ::" + jClasses.get(i)); 

       if((null != jClasses.getClass().getInterfaces()[i])) { 
        System.out.println(jClasses.getClass().getInterfaces()[i]); 
       } else { 
        System.out.println("No connection"); 
       } 
      } 

    public static List getClasseNames(String jarName) { 
     ArrayList classes = new ArrayList(); 

     try { 
      JarInputStream jarFile = new JarInputStream(new FileInputStream(
        jarName)); 
      JarEntry jarEntry; 

      while (true) { 
       jarEntry = jarFile.getNextJarEntry(); 
       if (jarEntry == null) { 
        break; 
       } 
       if (jarEntry.getName().endsWith(".class")) { 

        classes.add(jarEntry.getName().replaceAll("/", "\\.")); 
       } 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return classes; 
    } 

выход:

Print Classes ::com.java.testclient.PTest1.class 
interface java.util.List 
====== 
Print Classes ::com.java.testclient.ClassSpy.class 
interface java.util.RandomAccess 
====== 
Print Classes ::com.java.testclient.myInt.class 
interface java.lang.Cloneable 
====== 
Print Classes ::com.java.testclient.PTest.class 
interface java.io.Serializable 

Просьба предложить.

+0

Что такое 'getClasseNames' и это' jClasses.getClass() getInterfaces() [я. ] 'является подозрительным,' jClasses.get (i) .getClass(). getInterfaces() 'возможно –

+0

' getClasseNames' фактически включен в опубликованный код. – lexicore

+0

@lexicore не было [до] (http://stackoverflow.com/posts/41334032/timeline): p –

ответ

2

Вы можете использовать этот класс:

package io.github.gabrielbb.java.utilities; 

import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.net.URL; 
import java.net.URLClassLoader; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.jar.JarEntry; 
import java.util.jar.JarInputStream; 

/** 
* @author Gabriel Basilio Brito 
* @since 12/26/2016 
* @version 1.1 
*/ 
public class ClassesAndInterfacesFromJar { 

    public static List<Class> getJarClasses(String jarPath) throws IOException, ClassNotFoundException { 
     File jarFile = new File(jarPath); 
     return getJarClasses(jarFile); 
    } 

    public static List<Class> getJarClasses(File jar) throws IOException, ClassNotFoundException { 
     ArrayList<Class> classes = new ArrayList(); 
     JarInputStream jarInputStream = null; 
     URLClassLoader cl; 

     try { 
      cl = URLClassLoader.newInstance(new URL[]{new URL("jar:file:" + jar + "!/")}); // To load classes inside the jar, after getting their names 

      jarInputStream = new JarInputStream(new FileInputStream(
        jar)); // Getting a JarInputStream to iterate through the Jar files 

      JarEntry jarEntry = jarInputStream.getNextJarEntry(); 

      while (jarEntry != null) { 
       if (jarEntry.getName().endsWith(".class")) { // Avoiding non ".class" files 
        String className = jarEntry.getName().replaceAll("/", "\\."); // The ClassLoader works with "." instead of "/" 
        className = className.substring(0, jarEntry.getName().length() - 6); // Removing ".class" from the string 
        Class clazz = cl.loadClass(className); // Loading the class by its name 
        classes.add(clazz); 
       } 

       jarEntry = jarInputStream.getNextJarEntry(); // Next File 
      } 
     } finally { 
      if (jarInputStream != null) { 
       jarInputStream.close(); // Closes the FileInputStream 
      } 
     } 
     return classes; 
    } 

    // Main Method for testing purposes 
    public static void main(String[] args) { 
     try { 
      String jarPath = "C://Test.jar"; 
      List<Class> classes = getJarClasses(jarPath); 

      for (Class c : classes) { 
       // Here we can use the "isInterface" method to differentiate an Interface from a Class 
       System.out.println(c.isInterface() ? "Interface: " + c.getName() : "Class: " + c.getName()); 
      } 
     } catch (Exception ex) { 
      System.err.println(ex); 
     } 
    } 

Его можно найти по адресу:

https://github.com/GabrielBB/Java-Utilities/blob/master/ClassesAndInterfacesFromJar.java

+0

Спасибо Габриэль. :) – Ronak

Смежные вопросы