当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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. 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. 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. 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. This is similar to what Bukkit does (http://bukkit.org).

Thanks for you help,

Bart

网友答案:

Do you mean that you need to load jar files from a directory dynamicly?

The URLClassLoader may fit your needs.

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: