简体   繁体   中英

Java generic enum parameter where the enums have methods

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.

Just like other classes, enum s 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM