这是成功加载插件的代码(我知道这是因为我在插件中使用了记录器,并且在日志文件中看到了消息)。唯一的问题是,如果插件中的事件处理方法包含来自Minecraft forge来源的内容,它将不会调用该方法。
public void loadPlugin(File jar)
{
try
{
ClassLoader jarClassLoader=URLClassLoader.newInstance(new URL[]{jar.toURI().toURL()},getClass().getClassLoader());
Enumeration<JarEntry> jarEntries=new JarFile(jar).entries();
while(jarEntries.hasMoreElements())
{
JarEntry jarEntry=jarEntries.nextElement();
if(jarEntry.isDirectory()|!jarEntry.getName().endsWith(".class"))
continue;
Class aClass=jarClassLoader.loadClass(jarEntry.getName().substring(0,jarEntry.getName().length()-6).replace('/','.'));
if(aClass.isAnnotationPresent(PatchPlugin.class))
{
plugins.add(aClass);
EventHandler.passEvent(aClass,new LoadEvent());
}
}
}
catch(IOException|ClassNotFoundException ignored){}
}
并且此代码将事件传递给插件
public static boolean passEvent(Class plugin,Event event)
{
for(Method method:plugin.getDeclaredMethods())
{
if(method.isAnnotationPresent(EventTarget.class))
{
try
{
Class[] parTypes=method.getParameterTypes();
if(parTypes.length==1&parTypes[0].isInstance(event))
{
method.invoke(plugin.newInstance(),event);
return event.isCancelled();
}
}
catch(IllegalAccessException|InvocationTargetException|InstantiationException ignored){}
}
}
return false;
}