Java 程序在文件夹之间拆分

Java program split between folders

所以想开发一个小游戏引擎。它有主引擎 classes,例如 Vector 和 Actor 供用户使用。由于我只需要一次引擎,我想让游戏使用相同的引擎,并避免将所有游戏放在同一个 jar 中,我打算将它们放在单独的文件夹中,一个是引擎,然后是每个游戏的文件夹.然后引擎应该能够加载例如。播放器 class 从另一个文件夹中并使用它。

我认为一种解决方案是在 运行 时编译游戏文件夹。但是接下来的问题是文件相互依赖,并且依赖于已经加载到 JVM 中的已编译 classes。对于这种方法:

举个例子,我们有三个 classes:一个来自引擎的 Actor,一个由用户编写的扩展引擎 actor class 的 Player,以及第三个 class ,由用户编写的项目,在播放器中生成,但同样需要编译播放器,这意味着它们不能一个接一个地编译。

据我了解,当我们 运行 程序时,Actor 已经在 J​​VM 中编译了。现在我们知道了一个包含所有要编译的 class 的文件夹,其中 Player 依赖于 JVM 中已编译的 class 和文件夹中未编译的 class,这取决于 Player。

现在我想编译 Player class,因此我们还必须编译 Item,然后实例化 Player,这样我们就可以四处移动并生成物品。

这是我的意思的基本示例:

// already compiled in eg. executing jar file 
class MainStuff
{
    public static void main(String args[])
    {
        String FolderOfUncompiledClasses = "Some/folder/to/src/";
        Class<?>[] CompiledClasses = CompileFolderContents(FolderOfUncompiledClasses);
        // iterating through compiled classes
        for (Class<?> C : CompiledClasses)
        {
            // if we have an Actor class, we create a new instance
            if (C.isAssignableFrom(Actor.class))
            {
                try
                {
                    C.getDeclaredConstructor().newInstance();
                } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                        | InvocationTargetException | NoSuchMethodException | SecurityException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    // should compile all the files and returns the classes of the compiled java files

    private static Class<?>[] CompileFolderContents(String Folder)
    {
        File[] JavaFiles = new File(Folder).listFiles();

        Class<?>[] CompiledClasses = new Class<?>[JavaFiles.length];

        for (int i = 0; i < JavaFiles.length; i++)
        {
            Class<?> CompiledClass = DoCompilationStuff(JavaFiles[i]);
            CompiledClasses[i] = CompiledClass;
        }
        return CompiledClasses;
    }

    // this should effectively compile the class which it can both use non compiled
    // java files in the folder and already compiled classes
    private static Class<?> DoCompilationStuff(File ToCompile)
    {
        return null;
    }
}

// already compiled in eg. executing jar file
class Actor
{
    int X, Y;
}

在驱动器某处的文件夹中:

// not compiled
class Player extends Actor
{
    public Player()
    {
        // uses other non compiled class
        new Item();
    }
}

// not compiled
class Item
{
   // Also uses Actor so we can't compile them in series
   public Item(Player P)
   {
   }
}

我试过使用 javac 命令,但我无法以某种方式让它处理整个文件夹结构。

我希望我以合乎逻辑的方式解释它,如果这种方法没有意义。这只是一个想法,如果你有更好的方法,我会很高兴听到。

非常感谢!

如果您真的必须使用 javac,请将 类 保持在相同的 package 和目录中。这将简化构建过程,而不必使用 -cp 参数来指定存在于多个不同目录中的 class-path。

我建议您应该使用构建系统设置项目,而不是手动编译,例如Gradle. If you look at Building Java Applications Gradle 文档,大约需要 10 分钟,您应该拥有所需的一切:构建、测试和打包。