我需要从一个目录中的java文件中获取一个类的方法名。
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");
}我去叫ClassNotFoundException。
这是正确的做法吗?
有没有人能提出解决方案……
发布于 2010-03-09 16:40:50
您不能将.java文件作为类加载。您应该加载一个.class文件(这意味着应该首先编译它)
loader.loadClass("Arithmatic", true);如果没有编译形式的类,可以在运行时使用JavaCompiler对其进行编译
发布于 2010-03-09 16:39:46
试一试
Class.forName("Arithmatic", true, loader)而不是
loader.loadClass("Arithmatic.java")https://stackoverflow.com/questions/2407581
复制相似问题