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.

BKruger
  • 31
  • 4

1 Answers1

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);
    }
}
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213