如何使用Java读取Java文件结构?

Iso*_*Iso 4 java file

我正在尝试读取一个java文件,并在控制台中显示包,类和方法名称.这样的事情:

文件:Test.java

package tspec.test;

public class Test {
   public void addTest () {}
   public void deleteTest () {}
}
Run Code Online (Sandbox Code Playgroud)

输出:

package name: tspec.test
class name: Test
method name:
addTest
deleteTest
Run Code Online (Sandbox Code Playgroud)

提前致谢 :)

Ada*_*ter 6

这可以使用Java Compiler API(在Java 6中引入)来完成.不幸的是,这个解决方案仅限于Sun的JDK.因此,您必须安装JDK,并且必须将其tools.jar文件包含在类路径中.

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);
}
Run Code Online (Sandbox Code Playgroud)

当我传递此方法File的内容是您的样本时,我收到此输出:

class name: Test
method name:
addTest
deleteTest

不幸的是,我还没有弄清楚包名存储的位置.