如何获取 jar 中每个类的 Class 对象

发布于 2024-12-10 21:08:46 字数 405 浏览 0 评论 0原文

我有一个包含 30 个左右类的 jar 文件。我想要的是,在 main 方法的开头,我从该 jar 中调用一个类,该类使用 Java 的反射功能获取对 jar 中每个类的 Class 引用。我的最终目标是执行某种操作,查询为每个类定义的变量。基本上我正在寻找类似的东西。有没有一种简单的方法可以使用标准反射 API 来做到这一点,或者制定可行的解决方案会很麻烦?

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

编辑:

只是为了清楚起见:代码将从检查的 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

昇り龍 2024-12-17 21:08:46

这对我有用:

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);
    }
}

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);
    }
}
狠疯拽 2024-12-17 21:08:46

列出 JAR 文件中的所有类不是反射可以完成的事情。

但是,可以使用 JarInputStream

Listing all classes in a JAR file is not something that can be done with reflection.

However, it can be done using a JarInputStream.

长发绾君心 2024-12-17 21:08:46

以下解决方案适用于 classpath 中或 classpath 外部的 jar

 try {
        File pathToJar = new File("C:/some.jar");

        JarFile jarFile;
            jarFile = new JarFile(pathToJar);
        Enumeration<JarEntry> e = jarFile.entries();

        URL[] urls = { new URL("jar:file:" + pathToJar+"!/") };
        URLClassLoader cl = URLClassLoader.newInstance(urls);

        while (e.hasMoreElements()) {
            JarEntry je = e.nextElement();
            if(je.isDirectory() || !je.getName().endsWith(".class")){
                continue;
            }
            // -6 because of .class
            String className = je.getName().substring(0,je.getName().length()-6);
            className = className.replace('/', '.');
            System.out.println("Checking for class " + className);
            Class c = cl.loadClass(className);


            System.out.println("Class object " + c.getName());

        }
    } catch (IOException | ClassNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

The following solution will work with a jar that is in your classpath or outside your classpath.

 try {
        File pathToJar = new File("C:/some.jar");

        JarFile jarFile;
            jarFile = new JarFile(pathToJar);
        Enumeration<JarEntry> e = jarFile.entries();

        URL[] urls = { new URL("jar:file:" + pathToJar+"!/") };
        URLClassLoader cl = URLClassLoader.newInstance(urls);

        while (e.hasMoreElements()) {
            JarEntry je = e.nextElement();
            if(je.isDirectory() || !je.getName().endsWith(".class")){
                continue;
            }
            // -6 because of .class
            String className = je.getName().substring(0,je.getName().length()-6);
            className = className.replace('/', '.');
            System.out.println("Checking for class " + className);
            Class c = cl.loadClass(className);


            System.out.println("Class object " + c.getName());

        }
    } catch (IOException | ClassNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文