java NoClassDefFoundError。为什么?我该怎么修?
我写了我的类加载器:
package ru.sberbank.school.homework8;
import ru.sberbank.school.homework8.plugin.Plugin;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class PluginManager extends ClassLoader {
private final String pluginRootDirectory;
public PluginManager(String pluginRootDirectory) {
this.pluginRootDirectory = pluginRootDirectory;
}
public Plugin load(String pluginName, String pluginClassName) {
String name = pluginName + "." + pluginClassName;
try {
Class clazz;
try {
clazz = super.findSystemClass(name);
} catch (ClassNotFoundException e) {
String fileName = pluginRootDirectory + "\\" + pluginName + "\\" + pluginClassName + ".class";
try (FileInputStream fin = new FileInputStream(fileName)) {
byte[] buffer = new byte[(int) (new File(fileName).length())];
fin.read(buffer);
clazz = defineClass(name, buffer, 0, buffer.length);
}
}
return (Plugin)clazz.newInstance();
} catch (IOException | InstantiationException | IllegalAccessException ignored) {
return null;
}
}
}
当我运行它时:
package ru.sberbank.school.homework8;
import ru.sberbank.school.homework8.plugin.Plugin;
public class PluginManagerTest {
public static void main(String[] args) {
String pluginRootDirectory = "D:\\sbt\\target\\classes\\ru\\sberbank\\school\\homework8";
PluginManager pluginManager = new PluginManager(pluginRootDirectory);
Plugin plugin = pluginManager.load("plugin", "PluginImpl");
if (plugin != null) {
plugin.doUseful();
}
}
}
Exception in thread "main" java.lang.NoClassDefFoundError: plugin/PluginImpl (wrong name: ru/sberbank/school/homework8/plugin/PluginImpl) at java.lang.ClassLoader.defineClass1(Native Method)
我没有发现任何错误。为什么?我怎样才能修好它
请帮帮我
package ru.sberbank.school.homework8.plugin;
public class PluginImpl implements Plugin {
@Override
public void doUseful() {
System.out.println("My plugin!");
}
}
# 1 楼答案
之所以会出现这个错误,是因为您没有提供正确的类的FQN,实际上在
load
方法中,您试图找到与pluginName + "." + pluginClassName
相对应的类,在您的例子中plugin.PluginImpl
但是类的包名PluginImpl
实际上是ru.sberbank.school.homework8.plugin
,因此类的真正FQN是ru.sberbank.school.homework8.plugin.PluginImpl
要解决此问题,您需要更换:
与:
或者您可以修改方法
load
以添加前缀,前提是您总是从同一根包中检索插件: