3

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.

2 Answers 2

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

We should not forget to emphasize how dangerous method signatures, that can easily mixed up with the inherited Object.equals but have a different meaning, are…
@Holger Agreed. equals(TypeOtherThanObject) is a practice that the designers of Java SE learned early on was a bad idea.
0

With Java 8 you can do something like this:

interface TypeChecker {

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

Then you just need

enum SomeType implements TypeChecker {
    AAA, BBB
}

The drawback of this approach is that enum constants cannot have names that are different from their type strings. One workaround is to override toString for individual constants (or use a method other than toString as in VGR's solution). The problem with doing that is that it doesn't really cut down on the boilerplate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.