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
10) You can not create an instance of enums by using a new operator in Java because the constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself. 11) An instance of Enum in Java is created when any Enum constants are first called or referenced in code.
valueOf() method returns the enum constant of the specified enumtype with the specified name. The name must match exactly an identifier used to declare an enum constant in this type.
Enums are very powerful as they may have instance variables, instance methods, and constructors. Each enum constant should be written in capital letters. Every enum constant is by default internally public static final of type Enum declared.
values() method can be used to return all values present inside the enum. Order is important in enums.By using the ordinal() method, each enum constant index can be found, just like an array index. valueOf() method returns the enum constant of the specified string value if exists.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With