我有一个类加载器,它从 /plugins 文件夹中的所有 jar 文件加载“主”类,这假设所有 jar 都有包插件。(插件名称)包含名为 main 的类。每个主类都有一个名为 main 的构造函数。
类加载成功,但我需要知道如何从加载的类中调用主构造函数。
(此类/类在运行时加载)
我试过用这个:
Constructor c = cls.getConstructor(Integer.class); //line 41
Plugin plug = (Plugin) c.newInstance(0);
但我收到此错误:
java.lang.NoSuchMethodException: plugin.myplugin.main.<init>(java.lang.Integer)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
at hkr.classloader.PluginLoader.loadPlugins(PluginLoader.java:41)
at hkr.core.startup.InitializeGame.inigame(InitializeGame.java:32)
at hkr.launcher.main.LauncherMain.main(LauncherMain.java:16)
package hackers.classloader;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import org.java.plugin.Plugin;
public class PluginLoader
{
@SuppressWarnings({ "unused", "rawtypes", "resource" })
public static void loadPlugins() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
Class cls = null;
int x = hackers.core.startup.InitializeGame.map.size();
for (int i = 1; i<=x;i++)
{
String className = hackers.core.startup.InitializeGame.map.get(i + "");
File file = new File(System.getProperty("user.dir") + File.separator + "plugins" + File.separator + className + ".jar");
URL url = null;
try {
url = file.toURI().toURL();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
try {
cls = cl.loadClass("plugin." + className + ".main");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Constructor c = cls.getConstructor(Integer.TYPE);
Plugin plug = (Plugin) c.newInstance(0);
}
}
}