Being a hyper-pedantic note about turning bytes into Java strings and a small fix for a smaller and almost-purely-aesthetic but ubiquitous problem. [Update: Heavily revised with a better solution.]
[Most of the comments below apply to the original solution I’d been using, which turned out to be sub-optimal.]
So, it’s like this: You’ve received some bytes over the wire and run them through a JSON parser and you’re looking at a few of them that you know damn well are a field name in UTF-8. So, you say:
final String name = new String(bytes);
Then your perfectly sensible reviewer points out that it’s a Best Practice to call the constructor with the “charsetName” argument because otherwise it’ll use “the platform’s default charset”. Which you know damn well is UTF-8 but hey, a Best Practice is a Best Practice, so you say:
final String name = new String(bytes, "UTF8");
At which point your IDE sticks a sharp little red underline in your eye because hey, that might throw an UnsupportedEncodingException even though the Javadocs say explicitly that implementations must damn well support UTF-8.
Now your nice minimal code is wearing an ugly necklace of tries and catches. And what, I ask, is supposed to go in the catch clause? There’s only one thing you can be sure of: It’ll be ugly and distracting and useless. I mean, if you had a “detonateBioWeapon()” call, you could put it in there and still sleep soundly. Once my catch clause read:
throw new RuntimeException("Paging Mr Gosling to the white courtesy phone for a message.");
But another perfectly-reasonable reviewer made me take it out.
I bet there are millions of these stupid intrusive little excrescences all over the world’s Java code-bases. In the previous sentence, “millions” is not a figure of speech.
Anyhow, the answer is this:
import java.nio.charset.StandardCharsets; final String name = new String(bytes, StandardCharsets.UTF_8);
I can’t conceive of any circumstances in which any of the three versions of this code presented here will produce results different from any of the others. But hey, your Practices are the Best, baby.