Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Read Java File Structure using Java?

Tags:

java

file

I'm trying to read a java file and display in console the package, class and method name. something like this:

File: Test.java

package tspec.test;

public class Test {
   public void addTest () {}
   public void deleteTest () {}
}

Output:

package name: tspec.test
class name: Test
method name:
addTest
deleteTest

Thanks in advance :)

like image 402
Iso Avatar asked Jan 22 '23 06:01

Iso


2 Answers

This can be accomplished using the Java Compiler API (introduced in Java 6). Unfortunately, this solution is limited to Sun's JDK. Therefore, you will have to have that JDK installed and you must include its tools.jar file in your class path.

public void displayInformation(File javaSourceFile) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    // The file manager locates your Java source file for the compiler. Null arguments indicate I am comfortable with its default behavior.
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    // These will be parsed by the compiler
    Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjects(javaSourceFile);

    // Creates a new compilation task. This doesn't actually start the compilation process.
    // Null arguments indicate I am comfortable with its default behavior.
    CompilationTask task = compiler.getTask(null, null, null, null, null, fileObjects);

    // Cast to the Sun-specific CompilationTask.
    com.sun.tools.javac.api.JavacTaskImpl javacTask = (com.sun.tools.javac.api.JavacTaskImpl) task;

    // The Sun-specific JavacTaskImpl can parse the source file without compiling it, returning 
    // one CompilationUnitTree for each JavaFileObject given to the compiler.getTask call (only one in our case).
    Iterable<? extends CompilationUnitTree> trees = javacTask.parse();
    CompilationUnitTree tree = trees.iterator().next();

    // Create a class that implements the com.sun.source.tree.TreeVisitor interface.
    // The com.sun.source.util.TreeScanner is a good choice because it already implements most of the logic.
    // We just override the methods we're interested in.
    class MyTreeVisitor extends TreeScanner<Void, Void> {

        @Override
        public Void visitClass(ClassTree classTree, Void p) {
            System.out.println("class name: " + classTree.getSimpleName());
            System.out.println("method name:");
            return super.visitClass(classTree, p);
        }

        @Override
        public Void visitMethod(MethodTree methodTree, Void p) {
            System.out.println(methodTree.getName());
            return super.visitMethod(methodTree, p);
        }

    }

    tree.accept(new MyTreeVisitor(), null);
}

When I pass this method a File whose content is your sample, I receive this output:

class name: Test
method name:
addTest
deleteTest

Unfortunately, I haven't yet figured out where the package name is stored.

like image 85
Adam Paynter Avatar answered Feb 02 '23 21:02

Adam Paynter


  • Reflection and Introspection Java API's.

It's purpose is to introspect Java code and report back about it's contents. With Reflection you can do things like :

 Class.forName(className).getDeclaredMethods();
  • Java also has the Java Mirror API with similiar functionality, but is not as commonly used.

Both of these solutions require no 3rd party libraries or tools.

like image 38
rlb.usa Avatar answered Feb 02 '23 20:02

rlb.usa