Search code examples
javajakarta-eeenumsenumerationenumerate

How to return Enum if matches with given String


I have Enum class as given below

public enum AlgorithmEnum {

    SHA512("RSA", "SHA512", 1), SHA1("RSA", "SHA1", 1), SHA384("RSA", "SHA384", 1);

    private String keyAlgorithm;
    private String hashAlgorithm;
    private Integer key;

    private AlgorithmEnum(String keyAlgorithm, String hashAlgorithm, Integer key) {
        this.keyAlgorithm = keyAlgorithm;
        this.hashAlgorithm = hashAlgorithm;
        this.key = key;
    }

    public String getKeyAlgorithm() {
        return keyAlgorithm;
    }

    public void setKeyAlgorithm(String keyAlgorithm) {
        this.keyAlgorithm = keyAlgorithm;
    }

    public String getHashAlgorithm() {
        return hashAlgorithm;
    }

    public void setHashAlgorithm(String hashAlgorithm) {
        this.hashAlgorithm = hashAlgorithm;
    }

    public Integer getKey() {
        return key;
    }

    public void setKey(Integer key) {
        this.key = key;
    }
}

I need to have method something like below which takes input as string and returns Enum

public AlgorithmEnum getAlgorithm(String algorithm){
        //returns AlgorithmEnum object
    }

I would call above method by passing "SHA512withRSA" as input for getAlgorithm method.

I need help in implementing the getAlgorithm method.


Solution

  • You can have something like:

    public static AlgorithmEnum getAlgorithm(final String algorithm)
            throws IllegalArgumentException
        {
            for (final AlgorithmEnum algorithmEnum : AlgorithmEnum.values())
            {
                if (algorithm.equalsIgnoreCase(String.format("%swith%s", algorithmEnum.getHashAlgorithm(), algorithmEnum.getKeyAlgorithm())))
                {
                    return algorithmEnum;
                }
            }
            throw new IllegalArgumentException("Unknown algorithm: " + algorithm);
        }
    

    However, I will not suggest to use this approach. Instead use 2 different arguments instead of a single String.