0

Alright, so I have this jar file and I'd like to retrieve all the classes inside that jar.

I've seen some other questions, but, most of them require the class name or package name.

I'd like something that doesn't need this. Maybe a method that asks for the file path "example.jar", and then it returns a list with the various class names.

By the way, I don't really now if class name is the correct term, what i need is something like this "com.name.name1".

I would use the Strings retrieved from the jar with Reflection. The result would be loading a jar dynamically without the need of any classnames.

A. Dato
  • 11
  • 4

2 Answers2

1

A jar file is basically just a zip file. You can open it with ZipInputStream and scan the contents. Any files whose name ends with ".class" should be a class, and you can fairly easily reconstruct the package name etc.

Alternatively, if you want more information about the classes, you should probably use a library (like this one) that handles class parsing for you - it's relatively complex.

xs0
  • 2,990
  • 17
  • 25
  • I'm not sure if I am using the correct name, what I am trying to get from the jar is something like this "com.name.name1" and "com.name.name2 "to use them with Reflection. Now if I use this it works, the thing is I'd like to make this dynamic without the need to hardcode anything. – A. Dato Nov 13 '17 at 19:36
1

You can use JarFile#entries to get an enumeration of the ZIP file entries, than use a URLClassLoader to get the classes:

private List<Class<?>> loadClasses(String pathToJar) throws IOException, ClassNotFoundException {
    ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
    try (JarFile jarFile = new JarFile(pathToJar)) {
        URL[] urls = { new URL("jar:file:" + pathToJar + "!/") };
        URLClassLoader loader = URLClassLoader.newInstance(urls);

        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entryName = entry.getName();

            if (entry.isDirectory() || !entryName.endsWith(".class"))
                continue;

            String className = entryName.replaceAll("\\.class$", "").replace('/', '.');
            Class<?> clazz = loader.loadClass(className);
            classes.add(clazz);
        }
    }
    return classes;
}
Cardinal System
  • 2,749
  • 3
  • 21
  • 42