简体   繁体   中英

How to return an instance from Enum?

Consider that I have 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 as

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 their instances when someone calls for example

Algorithm.SHA1.getInstance()

Question

  • How can I return the instance since my method is static? (It is static so that multiple threads can not play around with each other data)

You can't return an instance when your method is static, but you can make your enum implement an interface , and make an instance method that calls the static method perform the 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, like this:

Algorithm.HMAC.hash(someText, sb);

or pass around EncryptionAlgo instances, like this:

EncryptionAlgo algo = Algorithm.SHA1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM