[英]How To Load classes using ClassLoader
I have an interface named Operator the directory of this interface is d:\\operators Interface definition is like so : 我有一个名为Operator的接口,该接口的目录为d:\\ operators界面定义如下:
package operators;
public interface Operator
{
double calculate(double firstNumber,double secondNumber);
String getSign();
}
In the main program (d:\\ProjectFile94.6.7\\main) I want load this interface and use it .I load interface like so : 在主程序(d:\\ ProjectFile94.6.7 \\ main)中,我想加载此接口并使用它。
String rootPath = System.getProperty("user.dir")+System.getProperty("file.separator");
String operatorsPath = rootPath.replace("ProjectFile94.6.7" , "").replace("main" , "") + "operators";
System.out.println(operatorsPath);
//Load operators from another file
File operatorFile = new File(operatorsPath);
URL operatorFilePath = operatorFile.toURL();
URL[] operatorFilePaths = new URL[]{operatorFilePath};
ClassLoader operatorsLoader = new URLClassLoader(operatorFilePaths);
Class operatorInterface = operatorsLoader.loadClass("operators.Operator");
The app compiled fine but at runtime I got this exception : 该应用程序编译良好,但在运行时出现此异常:
java.lang.ClassNotFoundException : operators.Operator
java.lang.ClassNotFoundException:operator.Operator
You must not append the package name in the classpath directory: 您不得将包名称附加在classpath目录中:
String operatorsPath = rootPath.replace("ProjectFile94.6.7" , "").replace("main" , "");
ie the directory path should be just D:/
. 即目录路径应该只是
D:/
。 Otherwise, you're just telling the classloader to search for D:/operators/operators/Operator.class
. 否则,您只是在告诉类加载器搜索
D:/operators/operators/Operator.class
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.