Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clean way to implement similar enum types in Java

Tags:

java

enums

I have multiple enum types, a typical implementation is as follows.

public enum SomeType {
    TYPE_A("aaa"),
    TYPE_B("bbb"),

    private final String type;

    private SomeType(String type) { this.type = type; }

    public boolean equals(String otherType) {
        return (otherType == null) ? false : type.equals(otherType.toUpperCase());
    }
}

Other than specific enum types, the constructor and methods (i.e., equals and a few more) are the same for these enums. I cant create a super "class" and extends from it. Is there a clean solution so that I only need 1 copy of these methods and make all enum types inherit them? Thanks.

like image 463
hixhix Avatar asked Jul 01 '26 00:07

hixhix


1 Answers

Enum types are permitted to implement interfaces, like any other class. An example in Java SE is StandardCopyOption and LinkOption, which both implement CopyOption.

Although CopyOption doesn't have any methods, you certainly can define methods in such an inherited interface if you wish.

public interface TypedValue {
    String getType();

    default boolean equals(String otherType) {
        return otherType != null && getType().equals(otherType.toUpperCase());
    }
}

 

public enum SomeType
implements TypedValue {
    TYPE_A("aaa"),
    TYPE_B("bbb");

    private final String type;

    private SomeType(String type) { this.type = type; }

    @Override
    public String getType() {
        return type;
    }
}
like image 107
VGR Avatar answered Jul 02 '26 12:07

VGR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!