运行外部java类(项目)
我想从 java 项目内部运行外部 Java 项目(类)。我指的不是任何程序(例如 EXE 文件),而是 java 类(项目)。
假设您有字符串中的类文件路径:
String = "C:\\test\\test.class";
I want to run an external Java project (class) from inside a java project. I don't mean whatever program (eg. EXE files) but java classes (projects).
Let consider you have the class file path in a string:
String = "C:\\test\\test.class";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是类加载器的职责。如果您在磁盘上有想要实例化/使用的外部
.class
文件,那么一旦您了解了可用的 API,事情就会相对简单:This is the responsibility of the
ClassLoader
. If you have external.class
files on disk that you want to instantiate/use, then it's relatively straightforward once you're aware of the available APIs:除了你相当苛刻的语气之外,你似乎还想要某种插件结构。
基本上,您需要一个 ClassLoader 来加载您想要的类/库。一旦它们被加载,您就可以使用它们。
也许这对您有帮助:如何在运行时加载 jar 文件
Besides your quite demaninding tone it seems as if you want some kind of plugin structure.
Basically, you'd need a
ClassLoader
that will load the classes/libaries you want. Once they are loaded you can use them.Maybe this helps you: How to load a jar file at runtime
“运行”另一个java程序是通过调用它的main方法来完成的。假设您有要运行的类 net.tilialacus.TheProg ,那么您可以(在您的其他 java 程序中)执行操作,
或者如果该类在编译时未知,则可以通过反射:
当然,如果该类您需要处理异常不存在或没有“public static main(String[])”方法。
"Running" another java program is done by invoking it's main method. Say you have the class net.tilialacus.TheProg that you want to run, then you can do (in your other java program)
or via reflection if the class is not known at compile time:
Of course you need to handle exceptions if the class does not exist or is does not have a "public static main(String[])" method.