Base64 have many static encode methods returning byte[] as
Base64.encodeBase64(stringToEncode.getBytes(StandardCharsets.UTF_8.name()));
Also MessageDigest using static getInstance
to encode/digest
But Hex doesn't, it have only instance method encode which requires to create an instance
new Hex().encode(stringToEncode.getBytes(StandardCharsets.UTF_8.name()));
Is there a reason I need to create instance to get byte array or is there a better way?
I currently don't think adding getBytes()
is a good idea, for example
Hex.encodeHexString(stringToEncode).getBytes()
There's no static method for you to use, but the class is thread-safe so you can just create an instance of it and keep it around.
It's a common idiom with some classes like ObjectMapper
or formatting objects for example. Of course they usually have more internal state than Hex
needs, so maybe this was a design oversight.
I believe the reason for these being instance methods is that the constructor takes a Charset
, which is required for converting chars to bytes. The alternative would've been to pass it as a parameter in a static method. Both could be implemented of course.