soha
soha

Reputation: 115

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 :

enter image description here

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

Upvotes: 1

Views: 536

Answers (1)

user207421
user207421

Reputation: 310860

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.

Upvotes: 1

Related Questions