java - Minecraft Forge 如何从外部 JAR 加载模组?

标签 java

如何从编译前不知道的外部 JAR 加载类?

问题归结为“如何获取 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();
}

最佳答案

也许可以试试这个。

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

希望这有帮助。

关于java - Minecraft Forge 如何从外部 JAR 加载模组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21506502/

相关文章:

java - Hadoop二级排序复合键compareTo与Custom Sorter比较实现

Java:向边框布局添加菜单栏

java - org.apache.jasper.JasperException : java. lang.ClassNotFoundException

java - 无锁并发栈实现

java - 检测密码加密类型——我可以将它们导入 Django 吗?

java - 无法在 ADT 中安装 wtp 组件

java - 事件发生后如何调整框架的大小?

java - 在JPA中,如何知道entityManager.persist(obj)是否已将对象持久化到数据库中?

java - SQLite 数据库查询多个表

java - 如何将库解压缩到临时目录,从该目录加载它及其所有依赖项