3

I'm looking for a java library to format/beautify Java code snippets. So for I have been using Google Java Format however it seems to work just for fully-fledged Java classes and not for code snippets. For example, the following code snippet has been formatted online without an issue:

@Bean public ConfigurableServletWebServerFactory webServerFactory() {
  JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
  factory.setPort(9000);
  factory.setContextPath("/myapp");
  factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html"));
  return factory;
}

But using Google Formatter, the following error is returned:

 error: class, interface, or enum expected

I've used the following code to attempt parsing it:

String formattedSource = new Formatter().formatSource(code);

Any idea how to fix it?

2
  • 1
    Take a look at org.eclipse.jdt.core.formatter.CodeFormatter. This plugin uses it github.com/revelc/formatter-maven-plugin/blob/main/src/main/… Commented Jun 13, 2021 at 10:23
  • Looks like the Google formatter only formats entire Java compilation units, not single methods. If you know it's a method, you could put a class declaration around the method before formatting. If the declaration that you put around it is properly formatted, the formatSource method shouldn't change it, so you can lift out the formatted method again after formatting. Commented Jun 14, 2021 at 0:07

1 Answer 1

1

Create custom template code as a full compilation unit and remove the template back to snippet after formatting.

see below

    public String formatSnippet(String snippet) throws FormatterException {
    final String CUNIT = "class code { public method() { /*;*/";
    String fCode = new Formatter().formatSource(CUNIT + snippet + "/*;*/}}");
    int startIndex = fCode.indexOf("/*;*/") + 5;
    int endIndex = fCode.indexOf("/*;*/", startIndex) - 1;
    return startIndex > 0 && endIndex > 0 && endIndex > startIndex ? fCode.substring(startIndex, endIndex) : snippet;
}
Sign up to request clarification or add additional context in comments.

2 Comments

A user will not accept an answer if it does not explain what it does. In other words, this answer is code-only. Please add an explanation to your answer.
Thank you for complying and giving an explanation to provide a better answer! +1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.