Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

java - Write generic method which takes enum and string as arguments

Please suggest. Suppose I have two enums as shown below. I'm performing tasks if enum values match my string.

public enum Action {
        DO("DO"),
        REDO("REDO"),
        ROLLBACK("DONT");

        private String value;

        private Action(String value) {
            this.value = value;
        }

        public String getValue() {
            return this.value;
        }
    }

public enum Days {
        WEEK("WORK"),
        LEAVE("DONT WORK");

        private String value;

        private Days(String value) {
            this.value = value;
        }

        public String getValue() {
            return this.value;
        }
    }

And I want below work to be generic for both cases:

//any String 
String sp ="do";

        Arrays.stream(Action.values()).forEach(e ->{
            if(e.getValue().equalsIgnoreCase(sp)){
                //System.out.println(sp); Some work to do here

            }
        } );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The only thing you need from both enums in this code:

    Arrays.stream(Action.values()).forEach(e ->{
        if(e.getValue().equalsIgnoreCase(sp)){
            //System.out.println(sp); Some work to do here

        }
    } );

is the getValue method.

So you can create an interface that has this method:

interface HasValue {
    String getValue();
}

Make both enums implement the interface:

public enum Action implements HasValue {
    ...
}

public enum Days implements HasValue {
    ...
}

Then you can write a generic method:

public <T extends HasValue> void foo(T[] values, String sp) {
    Arrays.stream(values).forEach(e ->{
        if(e.getValue().equalsIgnoreCase(sp)){
            //System.out.println(sp);

        }
    });
}

You can call it like this:

foo(Action.values(), sp);
foo(Days.values(), sp);

The method doesn't actually have to be generic. You could just do:

public void foo(HasValue[] values, String sp) {
    ...
}

If you can't change Days or Action, you can use a functional interface instead:

public <T> void foo(T[] values, Function<T, String> getValue, String sp) {
    Arrays.stream(values).forEach(e ->{
        if(getValue.apply(e).equalsIgnoreCase(sp)){
            //System.out.println(sp);

        }
    });
}

// usage:

foo(Action.values(), Action::getValue, sp);
foo(Days.values(), Days::getValue, sp);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...