I am trying to load a class dynamically using loadClass method of java ClassLoader in NetBeans IDE. When I run the following standalone program it gets executed properly and prints the output as expected:
public class StandaloneClass {
public static void main(String[] args) {
try {
String directory = "C:\\Workspace\\ProjectMeteor\\src\\java\\com\\meteor\\loader";
File file = new File(directory);
URL url = file.toURI().toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("com.meteor.loader.ClassToBeLoaded");
Object o = cls.newInstance();
System.out.println("Class Loaded: " + o.getClass().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:- Class Loaded: class com.meteor.loader.ClassToBeLoaded
But when I run the same piece of code (in a web application) its throwing ClassNotFoundException.
@Path("/test")
public class DynamicWebClass {
@GET
@Path("/getFileExplorerNodes")
@Produces(MediaType.TEXT_PLAIN)
public String getFileExplorerNodes() {
try {
String directory = "C:\\Workspace\\ProjectMeteor\\src\\java\\com\\meteor\\loader";
File file = new File(directory);
URL url = file.toURI().toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("com.meteor.loader.ClassToBeLoaded");
Object o = cls.newInstance();
return o.getClass().toString();
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
}
Output:-
java.lang.ClassNotFoundException: com.meteor.loader.ClassToBeLoaded
Why is it throwing exception in web application when it is working fine in standalone program? How to fix this issue and make it run properly in a web application as well?
Looks like problem with the URL provided to the Class loader. Please provide a relative URL
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.