1

我想通过使用读取其源文件来获取java.lang.Classa 的对象。classFileReader

实际上,我想methods, constructors, parent class, overridden methods and imported packages通过使用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();
    }
}
4

1 回答 1

4

类是从 .class 文件而不是 .java 文件加载的。你有两个选择:

1) 使用不同的 API,如AST解析,旨在读取和理解 .java 文件(但不执行其中的代码)

2) 以编程方式编译 .java 文件,然后读取 .class 文件。这是丑陋的,不稳定的,可怕的,充满了警告,可能不是你想做的。

于 2014-03-22T07:47:04.427 回答