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.
Top comments (5)
how to solve this formatting issue
converet this
To something similar to this
I'm not really sure. You could try to change around settings in Eclipse and export a working config.
When I run the java code in vscode it show the path of file in terminal along with output but I want clean terminal with output, can you help with this, I have searched everywhere but did not got any solution. Their are solution of internal consol but can there be solution for terminal?
Thanks, this was very useful!
How to invoke formatting in a file? Any shortcut?