简体   繁体   English

如何将 .class 文件加载到变量中?

[英]How do I load .class files into a variable?

I'm working on a text-based game as a practice project.我正在将基于文本的游戏作为练习项目。

I already managed to write an engine that displays information and handles user input.我已经设法编写了一个显示信息和处理用户输入的引擎。 It draws the games content from custom Scene classes.它从自定义Scene类中提取游戏内容。 More precisely, I have a Scene superclass and create child-classes, like EvilDungeon extends Scene , for the actual playable levels.更准确地说,我有一个Scene超类,并为实际可玩级别创建子类,如EvilDungeon extends Scene

All scenes are located in a "Scenes"-folder, but I want to be able to make game expansions later on by dropping additional.class files of new scenes into said folder.所有场景都位于“场景”文件夹中,但我希望以后能够通过将新场景的附加 .class 文件放入所述文件夹来进行游戏扩展。

My plan was to use loadClass when the game is started to add them to a Scene -array, but it requires the class names which I can't know, since there can a any random combination of scenes in the Scenes-folder.我的计划是在游戏开始时使用loadClass将它们添加到Scene -array,但它需要我不知道的 class 名称,因为场景文件夹中可以有任意随机组合的场景。

How can I load all scenes in the folder without knowing which scenes exactly are present?如何在不知道确切存在哪些场景的情况下加载文件夹中的所有场景? Can I retrieve the class name somehow?我能以某种方式检索 class 名称吗?

My plan was to use loadClass when the game is started to add them to a Scene-array, but it requires the class names which I can't know, since there can a any random combination of scenes in the Scenes-folder.我的计划是在游戏开始时使用 loadClass 将它们添加到场景数组,但它需要我不知道的 class 名称,因为场景文件夹中可以有任意场景的随机组合。

That's what Service Provider Interfaces are for.这就是服务提供者接口的用途。 Just define an interface for your plugins and use ServiceLoader to get an instance of each plug-in.只需为您的插件定义一个接口并使用ServiceLoader获取每个插件的实例。

The plug-in needs to provide a text-file in /META-INF/services named after the interface and containing the class which implements that interface (both names must be fully qualified).插件需要在 /META-INF/services 中提供一个以接口命名并包含实现该接口的 class 的文本文件(两个名称都必须完全限定)。 You'll find the details in the documentation of ServiceLoader .您将在ServiceLoader的文档中找到详细信息。

This gives you the ability to add plugins to the class-path.这使您能够将插件添加到类路径。 Eg you can run your application using something like java -cp myapp.jar;plugins/* my.app.Main , then all the plugin-Jars in folder plugin will be added to the class-path and are available to your application (for more information on the asterisk, see this answer ).例如,您可以使用类似java -cp myapp.jar;plugins/* my.app.Main之类的东西运行您的应用程序,然后文件夹 plugin 中的所有插件-Jar 将被添加到类路径中并可供您的应用程序使用(对于有关星号的更多信息,请参阅此答案)。

If you want to load plug-ins at runtime, you can use a URLClassLoader, eg read this question or thistutorial on how to use the URLClassLoader.如果您想在运行时加载插件,您可以使用 URLClassLoader,例如阅读这个问题或本教程了解如何使用 URLClassLoader。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM