简体   繁体   中英

How to load class from another package?

I want to load class from another package(operators is the package name) .I use this statment :

File operatorFile = new File(operatorPath);
URL operatorFilePath = operatorFile.toURL();          
URL[] operatorFilePaths = new URL[]{operatorFilePath};
ClassLoader operatorsLoader = new URLClassLoader(operatorFilePaths);

Class operatorInterface = operatorsLoader.loadClass("operators.Operator");

But at runtime I got this exception :

在此处输入图片说明

I don't know the way I call Is not correct or other problem Is there with my code .Can any one help me?

File operatorFile = new File(operatorPath);

This is already wrong. The File should be initialized with the directory that is at the top of the package structure. In this case, operatorPath/.. , assuming operatorPath is "operators" .

URL operatorFilePath = operatorFile.toURL();          
URL[] operatorFilePaths = new URL[]{operatorFilePath};
ClassLoader operatorsLoader = new URLClassLoader(operatorFilePaths);

Class operatorInterface = operatorsLoader.loadClass("operators.Operator");

Should work from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM