Uma tarefa que acontece ocasionalmente é a de encontrar uma classe dentro de arquivos JAR, a solução é algo como varrer o conteúdo do JAR como um Zip que é, e examinar os itens do arquivo, e neste exemplo como estou usando o nome das classes para instanciar objetos do tipo Class que representem a definição da classe, o jar em questão deve estar no classpath da aplicacação.
segue ae o código, divirtam-se
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class SaveMethodNames {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
String jarName = args[0];
String resultName = jarName + ".csv";
BufferedWriter writer = new BufferedWriter(new FileWriter(resultName));
writer.write("CLASSNAME,METHOD\r");
String output = null;
String[] classes = getClassNames(jarName);
for (int i = 0; i < classes.length; i++) {
System.out.println(classes[i]);
String[] methods = getMethodNames(classes[i]);
for (int j = 0; j < methods.length; j++) {
System.out.println("\t" + methods[j]);
output = classes[i] + "," + methods[j] + "\r";
writer.write(output);
}
}
writer.flush();
writer.close();
}
private static String[] getMethodNames(String className) {
Class classDef;
String[] result = new String[0];
try {
classDef = Class.forName(className);
Method[] methods = classDef.getMethods();
result = new String[methods.length];
for (int i = 0; i < methods.length; i++) {
result[i] = methods[i].toString();
}
} catch (Throwable e) {
System.out.println("not able to get the methods from : "
+ className);
}
return result;
}
public static String[] getClassNames(String jarName) throws IOException {
ZipFile jar = new ZipFile(jarName);
Enumeration entries = jar.entries();
String className = null;
ArrayList temp = new ArrayList();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (!entry.isDirectory()) {
if (isClassName(entry.getName())) {
className = formatClassName(entry.getName());
temp.add(className);
}
}
}
jar.close();
String[] result = new String[temp.size()];
result = (String[]) temp.toArray(result);
return result;
}
private static String formatClassName(String name) {
name = name.replaceAll("/", ".");
name = name.replaceAll(".class", "");
return name;
}
private static boolean isClassName(String name) {
return name.indexOf(".class") >= 0;
}
}
