我目前在第loadedClass = classLoader.loadClass("scripts.Compass");
行
不知何故,文件编译得很好但是当我尝试加载类时它不会工作,因为它说它缺少类com / deft / core / scripts / DeftScript
编译&实例化:
File script = new File("./plugins/Deft-Core/scripts/Compass.java");
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
List<String> optionList = new ArrayList<String>();
optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path") + ";./plugins/Deft-Core.jar"));
Iterable<? extends JavaFileObject> compilationUnit = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(script));
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null, compilationUnit);
if (task.call()) {
Object obj = null;
try {
URLClassLoader classLoader = new URLClassLoader(new URL[]{new File("./plugins/Deft-Core/").toURI().toURL()});
Class<?> loadedClass;
loadedClass = classLoader.loadClass("scripts.Compass");
obj = loadedClass.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | MalformedURLException e) {
e.printStackTrace();
}
if (obj instanceof DeftScript) {
DeftScript deftScript = (DeftScript)obj;
deftScript.onEnable();
}
} else {
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
System.out.format("Error on line %d in %s%n", diagnostic.getLineNumber(), diagnostic.getSource().toUri());
}
}
Compass.java
package scripts;
import com.deft.core.scripts.DeftScript;
public class Compass extends DeftScript {
@Override
public void onEnable() {
}
}
DeftScript.java
package com.deft.core.scripts;
public abstract class DeftScript {
public abstract void onEnable();
}
错误:
java.lang.NoClassDefFoundError: com/deft/core/scripts/DeftScript
at java.lang.ClassLoader.defineClass1(Native Method) ~[?:1.8.0_45]
at java.lang.ClassLoader.defineClass(Unknown Source) ~[?:1.8.0_45]
at java.security.SecureClassLoader.defineClass(Unknown Source) ~[?:1.8.0_45]
at java.net.URLClassLoader.defineClass(Unknown Source) ~[?:1.8.0_45]
at java.net.URLClassLoader.access$100(Unknown Source) ~[?:1.8.0_45]
at java.net.URLClassLoader$1.run(Unknown Source) ~[?:1.8.0_45]
at java.net.URLClassLoader$1.run(Unknown Source) ~[?:1.8.0_45]
at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_45]
at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_45]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_45]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_45]
at com.deft.core.main.DeftCore.onEnable(DeftCore.java:79) ~[?:?]
答案 0 :(得分:0)
在加载com.deft.core.scripts.DeftScript
之前,您需要先加载scripts.Compass
。或者,您可以确保将父类/ jar放在父类加载器路径中。