javajavacabstract-syntax-treejavap

.java file path to class name


What's the most efficient way of getting the class(es) created on a .java file? I have the .java file path and I need to get the class full name.

I can only remember:

  1. Compile it with JavaCompiler
  2. Using the file text to parse it with Eclipse ASTParser (or another)
  3. Infer the class name through part of the file path, but I don't know if this works for every cases
  4. Somehow, use a tool like javap (dind't really thought about this one)

EDIT

I have this file, located at C:\myfolder\MyClass.java (let's ignore package and folder association conventions):

package mypackage.mysubpackage;

public class MyClass 
{
    // my class implementation here

    public class MyInnerClass 
    {
        // my inner class implementation here
    } 
}

The full name of the classes declared in this file are:

  1. mypackage.mysubpackage.MyClass
  2. mypackage.mysubpackage.MyClass.MyInnerClass (I don't know if this one it's correct, but let's pretend it is)

How can I get those class when I only have the .java file path (C:\myfolder\MyClass.java) ?


Solution

  • The only way to reliably obtain the names of the classes (mind that it may also define interfaces) files a .java file declares would be to really parse the java language contained in that file.

    And even then you will need to know which compiler will be/has been used to compile the .java file, as a java compiler could use any naming convention it likes for anonymous classes (the Oracle compiler uses $1, $2..., but there is no strict need to mimic that behavior).

    Considering these obstacles I believe its very hard to do from the .java files contents and simply impossible with the .java files path alone.