Java classloader
I need to get method names of a class from a java file in a directory.
File file=new File("C:/class/");
try {
// Convert File to a URL
URL url = file.toURL(); // file:/c:/class/
URL[] urls = new URL[]{url};
// Create a new class loader with the directory
URLClassLoader loader = new URLClassLoader(urls);
// Load in the class; Class.childclass should be located in
// the directory file:/c:/class/
Class cls = loader.loadClass("Arithmatic.java");
Method[] methods=cls.getMethods();
for(Method method:methods){
System.out.println("Method name:"+method.getName());
}
} catch (MalformedURLException e) {
System.out.println("Exception");
} catch (ClassNotFoundException e) {
System.out.println("Class not found exception");
}
开发者_如何学运维
I am getting ClassNotFoundException
.
Is this is the correct way of doing?
Can any body suggest the solution please...
You can't load a .java
file as class. You should load a .class
file (which means it should be compiled first)
loader.loadClass("Arithmatic", true);
In case you don't have the class in a compiled form, you can compile it at runtime using JavaCompiler
Try
Class.forName("Arithmatic", true, loader)
instead of
loader.loadClass("Arithmatic.java")
精彩评论