Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get Class object for every class in a jar

I have a jar file with 30 or so classes. What I want is that at the beginning of the main method I invoke a class from within this jar which using Java's reflection capabilities gets Class references to each class in the jar. My ultimate goal is to perform some sort of operation, querying a variable which is defined for every class. Basically I'm looking for something like. Is there an easy way to do this using the standard reflection APIs or it will be too much of a hassle to make a working solution?

List l = Reflection.getAllClasses();
String var;
foreach(Class c : l) { 
    var = c.getField("fieldname");
    doSomething(var);
}

Edit:

Just to make it clear: The code will be executed from withing the inspected jar.

like image 816
LordDoskias Avatar asked Oct 19 '11 11:10

LordDoskias


1 Answers

This does the trick for me:

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;


public class ClassFinder
{
    public static void main(String[] args) throws IOException
    {
    Collection<Class<?>> classes = new ArrayList<Class<?>>();

    JarFile jar = new JarFile("/home/nono/yamts/yamts.jar");
    for (Enumeration<JarEntry> entries = jar.entries() ; entries.hasMoreElements() ;)
    {
        JarEntry entry = entries.nextElement();
        String file = entry.getName();
        if (file.endsWith(".class"))
        {
            String classname = file.replace('/', '.').substring(0, file.length() - 6);
            try 
            {
                Class<?> c = Class.forName(classname);
                classes.add(c);
            }
            catch (Throwable e) 
            {
                System.out.println("WARNING: failed to instantiate " + classname + " from " + file);
            }
        }
    }

    for (Class<?> c : classes)
        System.out.println(c);
    }
}
like image 178
dagnelies Avatar answered Sep 24 '22 06:09

dagnelies