gpt4 book ai didi

java - 在应用程序编译中 - Java

转载 作者:行者123 更新时间:2023-11-30 06:56:58 26 4
gpt4 key购买 nike

我正在编写一个应用程序,其中有一个文本编辑器供用户编写自己的代码。然后我想编译上述代码,这很容易。我不知道该怎么做的技巧是从用户编译的代码中调用应用程序源中的函数

例如,如果我有一个名为“Player”的类,其函数为 MoveUp (); ,我如何从用户编译的代码中调用该函数?

最佳答案

如果您已经知道如何编译代码,并且知道编译后的类文件存储在哪里,那么实际上还不错。它只需要一点反射(reflection)。

    //replace filePath with the path to the folder where the class file is stored
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{filePath.toURI().toURL()});

//this actually loads the class into java so you can use it
Class<?> cs = Class.forName(compiledClassName, true, classLoader);

//the getConstructor method will return the constructor based on the
//parameters that you pass in. The default constructor has none, but if
//you want a different constructor you just pass in the class of the
//object you want to use
Constructor<?> ctor = cs.getConstructor();

//you can then just create a new instance of your class
Player player = (Player) ctor.newInstance();

//You can then call any methods on the Player object that you want.
player.MoveUp();

请记住,当您编译代码时,类包可以移动已编译类文件的位置。删除其代码的包语句,或者将包添加到您想要的位置可能会更容易。

顺便说一句,如果您要同时对多个“玩家”类执行此操作,则每个类都需要一个唯一的名称。如果他们没有,他们最终将共享相同的类文件,并且因此都具有相同的代码。

关于java - 在应用程序编译中 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41619744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com