检索从jar加载的类中的字段值

时间:2014-11-16 13:31:34

标签: java reflection instance classloader urlclassloader

我必须检索从jar加载的类中的所有字段的值。 所以我需要一个实例来做到这一点:

field.get(gameClassInstance);
每个字段

这里加载类并尝试创建实例的代码:

private Loader() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
    File jarFile = new File(System.getProperty("user.dir")+File.separator+"games"+File.separator+gameName+".jar");

    // Create the URLClassLoader
    URL url = jarFile.toURI().toURL();
    URL[] urls = new URL[]{url};
    URLClassLoader cl = new URLClassLoader(urls);

    // Search the class
    JarFile jar = new JarFile(jarFile.toString());
    Enumeration<JarEntry> e = jar.entries();
    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();
        if(je.isDirectory() || !je.getName().endsWith(".class")){
            continue;
        }
        if (je.getName().contains(gameName)){
            String className = je.getName().substring(0,je.getName().length()-6); // Remove ".class"
            className = className.replace('/', '.');
            gameClass = cl.loadClass(className);
            gameClassInstance = gameClass.newInstance(); // Create an instance of the class
        }
    }
    jar.close();
    cl.close();
}

这里加载的类:

public class Solitaire {

    public Board board = new Board("Board1", "");
    public Layout layout = new Layout();
    public Player player = new Player();

    public Solitaire() {
    }
}

在我创建实例的行上有一个StackOverflowError

1 个答案:

答案 0 :(得分:0)

我找到了问题的解决方案,我只是将字段设为静态并使用field.get(null)检索它们