1

I have 2 or more enums with the same methods in each. I need to use all these enums to validate a message in another class. Each enum have the same methods. I understand how to pass an enum as a generic parameter but I don't believe it is then possible to call that enum's method in the method that receives the enum as a generic enum.

3
  • 1
    Share some code Commented Feb 21, 2018 at 8:26
  • 7
    Use interfaces. Enums can implement interfaces. Commented Feb 21, 2018 at 8:26
  • 2
    Why would an Enum implement an Interface? Commented Feb 21, 2018 at 8:28

1 Answer 1

1

Just like other classes, enums can implement interfaces.

interface CanThing {
    void doThing(); 
}

enum Validate implements CanThing {
    ONE_THING {
        @Override
        public void doThing() {
            System.out.println("One thing");
        }
    },
    OTHER_THING;

    // Default.
    @Override
    public void doThing() {
        System.out.println("No thing");
    }
}

public void doAThing(CanThing thing) {
    thing.doThing();
}

public void test(String[] args) {
    for (CanThing t: Validate.values()) {
        doAThing(t);
    }
}
Sign up to request clarification or add additional context in comments.

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.