Question

I want to get the java.lang.Class object of a class by reading its source file using FileReader.

Actually I want to get all methods, constructors, parent class, overridden methods and imported packages of the class by selecting its source file using JFileChooser. So, I think I got these all things by using its class Class object methods like getConstructors() etc.

I have tried this, but it gives 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();
    }
}
Was it helpful?

Solution

Classes are loaded from .class files, not .java files. You have two options:

1) Use a different API, like AST parsing, which is designed to read and understand .java files (but not execute the code in them)

2) Programmatically compile the .java file, then read the .class file. This is ugly and wonky and horrible and full of caveats and probably not what you want to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top