我正在开展一个大学java项目,需要我实现一个简单的插件架构。项目A中的主要应用程序必须从位于另一个项目B中的指定目录加载插件。在对该主题(包括stackoverflow)进行了一些研究之后,我决定使用URLClassLoader来加载我可能然后实例化的类。项目B引用了项目A,所有插件都扩展了一个公共插件类(可能也是一个接口但不应该有任何区别)。这是我到目前为止所得到的:
我尝试加载的插件类的源代码:
package plugin;
import de.uks.student.pluginpattern.model.EditorPlugin;
public class Circle extends EditorPlugin
{
@Override
public void init()
{
}
}
和应该加载类的代码:
public void init(String[] args)
{
editorPane = new EditorPane().withWidth(500).withHeight(500);
toolBar = new ToolBar();
plugins = new EditorPluginSet();
// load plugins
File pluginDir = new File(PLUGIN_PATH);
if (!pluginDir.exists())
{
System.err.println("Plugin path not found!!");
return;
}
String[] plugins = pluginDir.list();
if (plugins == null)
{
System.err.println("Plugin path points to a file!!");
return;
}
for (String pluginString : plugins)
{
for (String argString : args)
{
if (pluginString.contains(argString))
{
System.out.println("Loading plugin from " + pluginString);
File pluginFile = new File(PLUGIN_PATH + "/");
// as getAbsolutePath embeds the relative path ... /../pluginProject ...
// which may not be processed correctly by the OS (Windows at least),
// we correct the path manually (just to be on the safe side)
String absolutePath = pluginFile.getAbsolutePath();
String[] split = absolutePath.split("\\\\");
List<String> splitsimpleList = Arrays.asList(split);
ArrayList<String> splitList = new ArrayList<>(splitsimpleList);
for (int i = 0; i < splitList.size() - 1; ++i)
{
if (splitList.get(i + 1).equals(".."))
{
splitList.remove(i);
splitList.remove(i);
break;
}
}
StringBuilder b = new StringBuilder();
for (String string : splitList)
{
b.append(string);
b.append("/");
}
File pluginFileForRealThisTime = new File(b.toString());
URL pluginURL = null;
try
{
pluginURL = pluginFileForRealThisTime.toURI().toURL();
} catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
URL[] urls = {pluginURL};
ClassLoader parentClassLoader = this.getClass().getClassLoader();
URLClassLoader uLoader = new URLClassLoader(urls, parentClassLoader);
Class<?> pluginClass = null;
try
{
String className = "plugin." + argString;
pluginClass = uLoader.loadClass(className);
} catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
现在我总是以ClassNotFoundException结束:
java.lang.ClassNotFoundException:plugin.Circle at java.net.URLClassLoader $ 1.run(未知来源)at java.net.URLClassLoader $ 1.run(未知来源)at java.security.AccessController.doPrivileged(Native Method)at java.net.URLClassLoader.findClass(未知来源)at java.lang.ClassLoader.loadClass(未知来源)at java.lang.ClassLoader.loadClass(未知来源)at de.uks.student.pluginpattern.model.EditorSystem.init(EditorSystem.java:412) 在 de.uks.student.pluginpattern.EditorSystem.main(EditorSystem.java:13)
我已经检查了
我几乎没有想过要尝试的其他方法。我做错了什么?
答案 0 :(得分:0)
我不得不将ClassLoader指向bin文件夹而不是bin / plugins文件夹