Carla
Carla

Reputation: 3380

How to format Java code snippets programmatically

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?

Upvotes: 3

Views: 643

Answers (1)

MoneyPenny
MoneyPenny

Reputation: 71

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;
}

Upvotes: 1

Related Questions