Java Compiler API (Java 6에서 소개 됨)을 사용하여 수행 할 수 있습니다. 불행하게도이 솔루션은 Sun의 JDK로 제한됩니다. 따라서 해당 JDK가 및으로 설치되어 있어야하며 클래스 경로에 tools.jar
파일을 포함시켜야합니다. 패키지 이름이 저장되는 위치
class name: Test
method name:
addTest
deleteTest
은 불행히도, 난 아직 파악되지 않은 : 나는 File
내용이 샘플이 방법을 전달하는 경우
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);
}
는,이 출력이 나타납니다.
"Java 파일 읽기"는 Java 소스 코드 파일 (.java) 또는 Java 바이트 코드 파일 (.class)을 의미합니까? –
.java 파일을 의미합니다. – Iso
'javac '소스를 살펴보고'.java' 파일을 파싱하는 방법을 볼 수 있습니다. 이 작업을 간단하게 수행하고 있습니까? 아니면 더 큰 프로젝트의 일부입니까? –