我正在尝试构建一个解析项目所有文件并对其进行一些更改的插件,我能够进行更改,但我的问题是ASTRewrite仅对文件进行更改在编辑器中打开。有没有办法对所有文件进行更改,即使它们没有在编辑器中打开? 任何帮助都非常感谢,提前感谢!
以下是我使用的示例代码:
//create a ASTRewrite
AST ast = cu.getAST();
ASTRewrite rewriter = ASTRewrite.create( ast );
//for getting insertion position
TypeDeclaration typeDecl = (TypeDeclaration) cu.types().get( 0 );
MethodDeclaration methodDecl = typeDecl.getMethods()[ 0 ];
Block block = methodDecl.getBody();
block.accept( new ASTVisitor(){
@Override
public boolean visit( InfixExpression node ){
//filter only those compound statements which start with logger
if( node.getParent().toString().startsWith( varLogger ) ){
loggerStmtList.add( node );
//checking if left operand is present in the logger infix statement
if(node.getLeftOperand() != null) {
//adding '[' to the leftOperand before "
Expression leftOperand = node.getLeftOperand();
StringBuilder leftOp = new StringBuilder(leftOperand.toString());
char[] c = {' ', '['};
leftOp.setCharAt(leftOp.toString().length() - 2, '[');
//leftOp.insert(leftOp.toString().length()-1, c);
//adding '[' the left operand source code
InfixExpression placeHolder2 = (InfixExpression) rewriter.createStringPlaceholder( leftOp.toString() , ASTNode.INFIX_EXPRESSION );
rewriter.replace( node.getLeftOperand(), placeHolder2, null );
}
//checking if right operand(extended operand) is present in the logger infix statement
if(! node.extendedOperands().isEmpty()){
//adding ']' to the rightOperand after "
List<String> rightOperand = new ArrayList<String>();
rightOperand.add(node.extendedOperands().get(0).toString());
StringBuilder rightOp = new StringBuilder(rightOperand.get(0).toString());
rightOp.setCharAt( 1, ']');
//adding ']' in the Extended operands(right side) source code
ListRewrite listRewrite = rewriter.getListRewrite(node, InfixExpression.EXTENDED_OPERANDS_PROPERTY);
InfixExpression placeHolder = (InfixExpression) rewriter.createStringPlaceholder( rightOp.toString() , ASTNode.INFIX_EXPRESSION );
listRewrite.replace( (ASTNode) node.extendedOperands().get( 0 ) , placeHolder , null );
rightOperand.clear();
}
TextEdit edits;
try{
edits = rewriter.rewriteAST();
// apply the text edits to the compilation unit
Document document = new Document(unit.getSource());
edits.apply(document);
// this is the code for adding statements
unit.getBuffer().setContents(document.get());
System.out.println("rewriting done");
}
catch( JavaModelException | IllegalArgumentException | MalformedTreeException | BadLocationException e ){
e.printStackTrace();
}
}
return false;
}
} );