栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Eclipse之外的项目中使用Java Eclipse抽象语法树?(即不是eclipse插件)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Eclipse之外的项目中使用Java Eclipse抽象语法树?(即不是eclipse插件)

给定一个Java 1.5文件,以下是我用来执行此操作的代码。我对此很陌生,今天花了很多时间浏览并尝试使下面的代码正常工作。

public void processJavaFile(File file) {    String source = FileUtils.readFileToString(file);    document document = new document(source);    ASTParser parser = ASTParser.newParser(AST.JLS3);    parser.setSource(document.get().toCharArray());    CompilationUnit unit = (CompilationUnit)parser.createAST(null);    unit.recordModifications();    // to get the imports from the file    List<importDeclaration> imports = unit.imports();    for (importDeclaration i : imports) {        System.out.println(i.getName().getFullyQualifiedName());    }    // to create a new import    AST ast = unit.getAST();    importDeclaration id = ast.newimportDeclaration();    String classToimport = "path.to.some.class";    id.setName(ast.newName(classToimport.split("\.")));    unit.imports().add(id); // add import declaration at end    // to save the changed file    TextEdit edits = unit.rewrite(document, null);    edits.apply(document);    FileUtils.writeStringToFile(file, document.get());    // to iterate through methods    List<AbstractTypeDeclaration> types = unit.types();    for (AbstractTypeDeclaration type : types) {        if (type.getNodeType() == ASTNode.TYPE_DECLARATION) { // Class def found List<BodyDeclaration> bodies = type.bodyDeclarations(); for (BodyDeclaration body : bodies) {     if (body.getNodeType() == ASTNode.METHOD_DECLARATION) {         MethodDeclaration method = (MethodDeclaration)body;         System.out.println("name: " + method.getName().getFullyQualifiedName());     } }        }    }}

这需要以下库:

commons-io-1.4.jarorg.eclipse.jdt.core_xxxx.jarorg.eclipse.core.resources_xxxx.jarorg.eclipse.core.jobs_xxxx.jarorg.eclipse.core.runtime_xxxx.jarorg.eclipse.core.contenttype_xxxx.jarorg.eclipse.equinox.common_xxxx.jarorg.eclipse.equinox.preferences_xxxx.jarorg.eclipse.osgi_xxxx.jarorg.eclipse.text_xxxx.jar


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/428082.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号