How to format Java Code by using Eclipse JDT?

If you use eclipse, you probably format your code by pressing Ctrl+Shift+F or right clicking Source -> Format very often. This function is also provide in JDT, so you can also format your Java code in Java code.

Finding the correct JDT API for doing this job, however, is not straight-forward. In the following code, you will see one of the classes being used is actually an internal class.

The following is the code to format Java code by using DefaultCodeFormatter.

import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.text.edits.MalformedTreeException;
import org.eclipse.text.edits.TextEdit;
public class FormatterTest {
	public static void main(String[] args) {
		String code = "public class TestFormatter{public static void main(String[] args){System.out.println(\"Hello World\");}}";
		CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(null);
		TextEdit textEdit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0, null);
		IDocument doc = new Document(code);
		try {
		} catch (MalformedTreeException e) {
		} catch (BadLocationException e) {

The apply() method in TextEdit class is the key to this problem. It applies the edit tree rooted by this edit to the GIVEN document.

Output in console:


Depends your eclipse version, you will need the following jar files:

  1. org.eclipse.core.contenttype_3.4.1.R35x_v20090826-0451.jar
  2. org.eclipse.core.jobs_3.4.100.v20090429-1800.jar
  3. org.eclipse.core.resources_3.5.2.R35x_v20091203-1235.jar
  4. org.eclipse.equinox.common_3.5.1.R35x_v20090807-1100.jar
  5. org.eclipse.equinox.preferences_3.2.301.R35x_v20091117.jar
  6. org.eclipse.jdt.core_3.5.2.v_981_R35x.jar
  7. org.eclipse.osgi_3.5.2.R35x_v20100126.jar
  8. org.eclipse.text_3.5.101.v20110928-1504.jar
  9. org.eclipse.core.runtime_3.5.0.v20090525.jar

If the above code is not clear to you, you may find this post very useful.

Category >> Java Development Tools (JDT)  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. subodhomjoshi82 on 2014-10-17

    But if you will check if you will add generics in your code above code will fail to format the code

Leave a comment