public class JavaParser {
private static final String path = "User.java";
private JavacFileManager fileManager;
private JavacTool javacTool;
public JavaParser() {
Context context = new Context();
fileManager = new JavacFileManager(context, true, Charset.defaultCharset());
javacTool = new JavacTool();
}
public void parseJavaFiles() {
Iterable<!--? extends JavaFileObject--> files = fileManager.getJavaFileObjects(path);
JavaCompiler.CompilationTask compilationTask = javacTool.getTask(null, fileManager, null, null, null, files);
JavacTask javacTask = (JavacTask) compilationTask;
try {
Iterable<!--? extends CompilationUnitTree--> result = javacTask.parse();
for (CompilationUnitTree tree : result) {
tree.accept(new SourceVisitor(), null);
}
} catch (IOException e) {
e.printStackTrace();
}
}
static class SourceVisitor extends TreeScanner<void, void=""> {
private String currentPackageName = null;
@Override
public Void visitCompilationUnit(CompilationUnitTree node, Void aVoid) {
return super.visitCompilationUnit(node, aVoid);
}
@Override
public Void visitVariable(VariableTree node, Void aVoid) {
formatPtrln("variable name: %s, type: %s, kind: %s, package: %s",
node.getName(), node.getType(), node.getKind(), currentPackageName);
return null;
}
}
public static void formatPtrln(String format, Object... args) {
System.out.println(String.format(format, args));
}
public static void main(String[] args) {
new JavaParser().parseJavaFiles();
}
}</void,>
package com.ragnarok.javaparser;
import com.sun.istack.internal.Nullable;
import java.lang.Override;
public class User {
@Nullable
private String foo = "123123";
private Foo a;
public void UserMethod() {}
static class Foo {
private String fooString = "123123";
public void FooMethod() {}
}
}
variable: foo, annotaion: Nullable variable name: foo, type: String, kind: VARIABLE, package: com.ragnarok.javaparser variable name: a, type: Foo, kind: VARIABLE, package: com.ragnarok.javaparser
@Override
public Void visitClass(ClassTree node, Void aVoid) {
formatPtrln("class name: %s", node.getSimpleName());
for (Tree member : node.getMembers()) {
if (member instanceof VariableTree) {
VariableTree variable = (VariableTree) member;
List<!--? extends AnnotationTree--> annotations = variable.getModifiers().getAnnotations();
if (annotations.size() > 0) {
formatPtrln("variable: %s, annotaion: %s", variable.getName(), annotations.get(0).getAnnotationType());
} else {
formatPtrln("variable: %s", variable.getName());
}
}
}
return super.visitClass(node, aVoid);
}
class name: User variable: foo, annotaion: Nullable variable: a class name: Foo variable: fooString
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有