Eclipse code fomatter not working for Java Generic

2020-07-17 15:37发布

问题:

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

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

And when i am trying to format the below code

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 eclipse code format not able to format code when i added generics . Can anyone tell what will be solution of this problem.

回答1:

You are not specifying any source level or compliance level options to ToolFactory.createCodeFormatter so you are probably getting a formatter that only supports the original Java without generics.

The JavaDoc for ToolFactory.createCodeFormatter says:

The given options should at least provide the source level (JavaCore.COMPILER_SOURCE), the compiler compliance level (JavaCore.COMPILER_COMPLIANCE) and the target platform (JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM). Without these options, it is not possible for the code formatter to know what kind of source it needs to format.

So you need to do that.



标签: java eclipse