简体   繁体   English

在Jar文件中加载类

[英]Load Class within Jar file

I'm trying to create a module system for my java application that will load Modules (Just jar files) in a directory. 我正在尝试为我的java应用程序创建一个模块系统,它将在目录中加载模块(Just jar文件)。 Each module will have a config.yml in it to link to the main class IE if the main class is in com.example.core and the main class was named 'Main', it would have com.example.core.Main in it. 如果主类在com.example.core中并且主类名为'Main',那么每个模块都将有一个config.yml链接到主类IE,它将包含com.example.core.Main 。 I've got it to load the yml file and I can get this property, but I can't work out how to load the class from a jar file. 我有它加载yml文件,我可以得到这个属性,但我无法弄清楚如何从jar文件加载类。 The main class will extend a class that is in the module loader application, named 'Module' so I need to keep the instance and put it in a Map, but all instances will extend Module. 主类将扩展模块加载器应用程序中的一个类,名为“Module”,因此我需要保留实例并将其放在Map中,但所有实例都将扩展Module。 This is similar to what Bukkit does ( http://bukkit.org ). 这类似于Bukkit所做的( http://bukkit.org )。

Thanks for you help, 谢谢你的帮助,
Bart 巴特

Do you mean that you need to load jar files from a directory dynamicly? 你的意思是你需要动态地从目录中加载jar文件吗?

The URLClassLoader may fit your needs. URLClassLoader可能符合您的需求。

Here is my example. 这是我的例子。

URL[] urls = ....
URLClassLoader loader = new URLClassLoader(urls);
Class<?> cls = loader.loadClass("com.example.core.Main");
Module module = (Module) cls.newInstance();

I hope that would be useful for you. 我希望这对你有用。

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

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