我需要从目录中的 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
。
这是正确的做法吗?
任何人都可以提出解决方案吗...
最佳答案
您不能将 .java
文件作为类加载。你应该加载一个 .class
文件(这意味着它应该首先被编译)
loader.loadClass("Arithmatic", true);
如果您没有编译形式的类,您可以在运行时使用 JavaCompiler
编译它
关于Java类加载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2407581/