Eclipse fomatter code not working for Java Generics code?

I am using the eclipse code format jar file to format java code and maven dependecy used below

<dependency> <groupId>org.eclipse.jdt</groupId> <artifactId>org.eclipse.jdt.core</artifactId> <version>3.7.1</version> </dependency> 

And when I try to format the code below

 package com.editor.test; 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 = "import java.util.Map; public class TestFormatter{public static void main(String[] args){Map<String,Object> map=null;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 { textEdit.apply(doc); System.out.println(doc.get()); } catch (MalformedTreeException e) { e.printStackTrace(); } catch (BadLocationException e) { e.printStackTrace(); } } } 

But the eclipse code format cannot format the code when I added generics. Can anyone say what will be the solution to this problem.

+3
java eclipse
source share
1 answer

You do not specify the source level or compliance level ToolFactory.createCodeFormatter , so you probably get a formatter that only supports original Java without generics.

The JavaDoc for ToolFactory.createCodeFormatter says:

These parameters should at least provide a source level (JavaCore.COMPILER_SOURCE), a compiler compliance level (JavaCore.COMPILER_COMPLIANCE) and a target platform (JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM). Without these options, it is impossible for the code formatter to know which source it needs to be formatted.

So you need to do this.

+3
source share

All Articles