How to configure VS Code Java formatting

I've been using VS Code for Java for the past year or so. For the most part, I've been super happy. But one thing has been driving me crazy.

The problem

I write a nicely formatted chain of methods, like:

public Weather getWeather(Double lat, Double lon) {
  return webClient.get()
      .uri(uri -> uri.path("/")
          .queryParam("lat", lat.toString())
          .queryParam("lon", lon.toString())
          .queryParam("units", "metric")
          .queryParam("apiKey", apiKey)
          .build())
      .retrieve()
      .toEntity(Weather.class)
      .block()
      .getBody();
}

But when I save the file, the formatter "helps" me out by smashing all of it on as few lines as possible:

public Weather getWeather(Double lat, Double lon) {
  return webClient.get()
      .uri(uri -> uri.path("/").queryParam("lat", lat.toString()).queryParam("lon", lon.toString())
          .queryParam("units", "metric").queryParam("apiKey", apiKey).build())
      .retrieve().toEntity(Weather.class).block().getBody();
}

The solution

The solution ended up being simple, just not that well documented. VS Code Java uses a headless Eclipse not only for Intellisense and other code actions, but also for code formatting.

A helpful Gist pointed to a way of using an Eclipse settings file to configure the formatter per project. But I wanted a solution that would work across projects. Finally, I found a super helpful Stack Overflow answer that outlined how to do just that.

1. Get a formatter config XML file

You can either use a formatter like the Google Java Style Guide (which I did) or export your Eclipse profile through Preferences > Java > Code Style > Formatter.

Save the file somewhere convenient where it won't get deleted. I chose ~/.vscode/eclipse-java-google-style.xml.

2. Change the join wrapped lines property to false

In the settings XML file, find the org.eclipse.jdt.core.formatter.join_wrapped_lines property, and set its value to false. Add the property if you don't have it.

<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="false"/>

3. Tell VS Code to use the format config

Open the VS Code settings (settings.json) and add the following line (remember to update the path):

"java.format.settings.url": "~/.vscode/eclipse-java-google-style.xml",

4. Profit

Restart VS Code. Change a Java file and the formatter should now produce a much nicer output.

17