skilcox
skilcox

Reputation: 3

How does Minecraft Forge load mods from external JARs?

How do I load a class from an external JAR that I'm not aware of prior to compiling?

The issue comes down to, "How do I get the path of a class in a jar?"

try {
    for (int x = 0; x < new File("mods").listFiles().length; x++) {
        if (new File("mods").listFiles()[x].getName().endsWith(".jar")) {

            JarFile file = new JarFile(new File("mods").listFiles()[x].getPath());
            Enumeration<JarEntry> entries = file.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                if (entry.getName().endsWith(".class")) {
                 new URLClassLoader(new URL[]{new URL("file://"+new File("mods").listFiles()[x].getAbsolutePath())}).loadClass(%path-to-class%);
                }
            }
            file.close();
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

Upvotes: 0

Views: 1927

Answers (1)

Sri Harsha Chilakapati
Sri Harsha Chilakapati

Reputation: 11950

Maybe try this.

try
{
    // Get all the files in mod folder
    File[] mods = new File("mod").listFiles();

    for (int i=0; i<mods.length; i++)
    {
        // Skip if the file is not a jar
        if (!mods[i].getName().endsWith(".jar"))
            continue;

        // Create a JarFile
        JarFile jarFile = new JarFile(mods[i]);

        // Get the entries
        Enumeration e = jarFile.entries();

        // Create a URL for the jar
        URL[] urls = { new URL("jar:file:" + mods[i].getAbsolutePath() +"!/") };
        cl = URLClassLoader.newInstance(urls);

        while (e.hasMoreElements())
        {
            JarEntry je = (JarEntry) e.nextElement();

            // Skip directories
            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('/', '.');

            // Load the class
            Class c = cl.loadClass(className);
        }
    }
}
catch (Exception e)
{
    e.printStackTrace();
}

Hope this helps.

Upvotes: 1

Related Questions