I have one java code to format the another java code programaticlly. The code is working fine for simple java code.But when i am introducing commnent in my input java code (input taken as String code) then in the following line textEdit is returned as null which is causing nullpointerexception in next steps.
TextEdit textEdit = codeFormatter.format(CodeFormatter.K_UNKNOWN , code, 0, code.length(), 0, null);
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 FormatCode {
public static void main(String[] args) {
String code = "public class TestFormatter{public static void main(String[] args){for(i=0;i<10;i++){i=i+2;\\abc"+"}System.out.println(\"Hello World\");}}";
CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(null);
TextEdit textEdit = codeFormatter.format(CodeFormatter.K_UNKNOWN , 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();
}
}
}
Any hint to solve this issue.
Use commenting in new line.
The //
comment is beeing used in one line so your code is like that.
In other words, to solve this issue, create /*
comments instead.