Friday, 21 October 2016

How to find list of all Class Names from inside .jar file?

Today we will see how to get list of all Class names from inside of .jar file. With the help of JarEntry and JarInputStream utility all classes inside jar can be extracted.

Let us see the example -

package com.mylogicalindian.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

public class JarClasses {

private static JarInputStream inputStream;

public static Map<String, Object> getListOfClasses(String fileName) throws FileNotFoundException, IOException{

Map<String, Object> map = new HashMap<String, Object>();
List<String> list = new ArrayList<String>();

inputStream = new JarInputStream(new FileInputStream(fileName));

JarEntry jarEntry;

while(true){

jarEntry = inputStream.getNextJarEntry();

if(jarEntry == null){
break;
}

if(jarEntry.getName().endsWith(".class")){

String className = jarEntry.getName().replaceAll("/", "\\.");
String myclass = className.substring(0, className.lastIndexOf("."));
list.add(myclass);

}

map.put("Jar File Name", fileName);
map.put("Classes", list);

}

return map;

}

public static void main(String args[]) throws FileNotFoundException, IOException{

String fileName = "C:/lib/ojdbc14.jar";
Map<String, Object> map = getListOfClasses(fileName);
System.out.println("Jar Name : " + map.get("Jar File Name"));
System.out.println("Classes : " + map.get("Classes").toString());
  System.out.println("No. of Classes present in "+map.get("Jar File Name")+" is "+((List)map.get("Classes")).size());

}

}

Output -

Jar Name : C:/lib/ojdbc14.jar
Classes : [oracle.net.TNSAddress.Address, oracle.net.TNSAddress.AddressList, oracle.net.TNSAddress.Description, oracle.net.TNSAddress.DescriptionList, oracle.net.TNSAddress.SOException, 
....
....
....
oracle.jdbc.OraclePreparedStatement, oracle.jdbc.OracleParameterMetaData, oracle.jdbc.OracleDatabaseMetaData, oracle.jdbc.OracleCallableStatement, oracle.jdbc.OracleTypes, oracle.jdbc.Const, oracle.jdbc.StructMetaData, oracle.jdbc.OracleDriver, oracle.jpub.runtime.MutableArray, oracle.jpub.runtime.Util, oracle.jpub.runtime.MutableStruct]
No. of Classes present in C:/lib/ojdbc14.jar is 623

No comments:

Post a Comment