我想通过使用 FileReader
读取其源文件来获取 class
的 java.lang.Class
对象。
实际上,我想通过使用 JFileChooser
选择其源文件来获取该类的所有方法、构造函数、父类、重写方法和导入包
。所以,我想我通过使用其类 Class
对象方法(如 getConstructors()
等)获得了所有这些东西。
我已经试过了,但是它给出了 java.lang.ClassNotFoundException
...
public static void main(String[] args) {
File file = new File(
"F:\\study\\projects\\saralbhakti\\src\\signup\\SignupServlet.java");
try {
// Convert File to a URL
URL url = file.toURL(); // file:/c:/myclasses/
URL[] urls = new URL[] { url };
// Create a new class loader with the directory
ClassLoader cl = new URLClassLoader(urls);
// Load in the class; MyClass.class should be located in
// the directory file:/c:/myclasses/com/mycompany
Class cls = cl.loadClass("signup.SignupServlet");
System.out.println("Class Name : " + cls.getName());
Method[] declaredMethods = cls.getDeclaredMethods();
System.out.println("All Methods : " + declaredMethods.length);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
最佳答案
类是从 .class 文件而不是 .java 文件加载的。您有两个选择:
1) 使用不同的 API,例如 AST解析,旨在读取和理解 .java 文件(但不执行其中的代码)
2) 以编程方式编译.java 文件,然后读取.class 文件。这是丑陋的、不稳定的、可怕的,充满了警告,可能不是你想做的。
关于java - 通过读取类的源(.java)文件获取类的 java.lang.Class 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22574881/