Add Comments by using Eclipse JDT ASTRewrite

This code example belongs to the Eclipse JDT tutorial series.

The goal of this code example is add a comment to the following code.

public class Main {
	public static void main(String[] args) {
		int i = 1;
		System.out.println(i);
	}
	public static void add() {
		int i = 1;
		System.out.println(i);
	}
}

After adding a comment before the first statement of the first method, it becomes the following:

public class Main {
	public static void main(String[] args) {
		//mycomment
		int i = 1;
		System.out.println(i);
	}
	public static void add() {
		int i = 1;
		System.out.println(i);
	}
}

In order to add a comment to java source code, we need to use ASTRewrite. The tutorial from eclipse programmer’s guide does not work. The main reason is missing of the following statement:

unit.getBuffer().setContents(document.get());

Here is the working code tested under Eclipse Indigo.

private void AddComments() throws MalformedTreeException, BadLocationException, CoreException {
 
	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("testAddComments");
	IJavaProject javaProject = JavaCore.create(project);
	IPackageFragment package1 = javaProject.getPackageFragments()[0];
 
	//get first compilation unit
	ICompilationUnit unit = package1.getCompilationUnits()[0];
 
	// parse compilation unit
	CompilationUnit astRoot = parse(unit);
 
	//create a ASTRewrite
	AST ast = astRoot.getAST();
	ASTRewrite rewriter = ASTRewrite.create(ast);
 
	//for getting insertion position
	TypeDeclaration typeDecl = (TypeDeclaration) astRoot.types().get(0);
	MethodDeclaration methodDecl = typeDecl.getMethods()[0];
	Block block = methodDecl.getBody();
 
	ListRewrite listRewrite = rewriter.getListRewrite(block, Block.STATEMENTS_PROPERTY);
	Statement placeHolder = (Statement) rewriter.createStringPlaceholder("//mycomment", ASTNode.EMPTY_STATEMENT);
	listRewrite.insertFirst(placeHolder, null);
 
	TextEdit 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("done");
}

#It is not necessary to run the code above inside an eclipse plug-in project, but it is easier to do so.

4 thoughts on “Add Comments by using Eclipse JDT ASTRewrite”

  1. Hi, I want to delete all comments from code(line comment,block comment and javadoc) i used BlockComment.getAlternateRoot().delete and node.delete, ASTrewrite ; but i failed.

Leave a Comment