0

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()
user207421
  • 305,947
  • 44
  • 307
  • 483
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • Why do you need them as bytes? It makes sense that `encodeHex` returns `char[]`, because the result is numbers and letters. Converting those to bytes seems highly unnecessary. – Kayaman Sep 27 '19 at 06:52
  • @kayaman I want to create a generic encoding method and other methods returns `bytes[]` – Ori Marko Sep 27 '19 at 06:56
  • @kayaman Can I suggest adding static method to library as enhancement? – Ori Marko Sep 27 '19 at 07:05
  • I don't see why not. You can even implement it yourself and submit it to them as a patch. – Kayaman Sep 27 '19 at 07:08

1 Answers1

1

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121