How to return an instance from Enum?

Note that I have an Algorithm enum as

 public enum Algorithm { SHA1("sha1"), HMAC("hmac"),; Algorithm(final String algorithm) { this.algorithm = algorithm; } private final String algorithm; public String getAlgorithm() { return algorithm; } } 

and I have different algorithms like

 public class Sha1 { public static String hash(final String text, final byte[] sb) {...} } 

and

 public class Hmac { public static String hash(final String text, final byte[] sb) {...} } 

I want to return my instances when someone calls for example

 Algorithm.SHA1.getInstance() 

Question

  • How to return an instance since my method is static? (This is static, so multiple threads cannot interact with each other).
+6
source share
1 answer

You cannot return an instance when your method is static, but you can make your enum interface implemented and create an instance method that invokes the static method, and does a virtual dispatch for you:

 public interface EncryptionAlgo { String hash(final String text, final byte[] sb); } public enum Algorithm implements EncryptionAlgo { SHA1("sha1") { public String hash(final String text, final byte[] sb) { return Sha1.hash(text, sb); } }, HMAC("hmac") { public String hash(final String text, final byte[] sb) { return Hmac.hash(text, sb); } }; Algorithm(final String algorithm) { this.algorithm = algorithm; } private final String algorithm; public String getAlgorithm() { return algorithm; } } 

Now you can call hash on the SHA1 or HMAC instance, for example:

 Algorithm.HMAC.hash(someText, sb); 

or bypass EncryptionAlgo instances, for example:

 EncryptionAlgo algo = Algorithm.SHA1; 
+6
source

Source: https://habr.com/ru/post/987538/


All Articles