Retrieve the value of fields in a class loaded from a jar

72 views Asked by At

I have to retrieve the value of all fields in a class loaded from a jar. So I need an instance to do that :

field.get(gameClassInstance);

for each field.

Here the code that load the class and try to create an instance :

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

Here the loaded class :

public class Solitaire {

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

    public Solitaire() {
    }
}

There is a StackOverflowError at the line where I create an instance.

1

There are 1 answers

0
Spooky On BEST ANSWER

I found the solution to my problem, I just make the fields static and retrieve them with field.get(null)