
给定一个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
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)