Iterate enum values using java generics

前端 未结 10 998
余生分开走
余生分开走 2020-12-02 10:55

I\'m trying to find a way to iterate through an enum\'s values while using generics. Not sure how to do this or if it is possible.

The following code illustrates

10条回答
  •  抹茶落季
    2020-12-02 11:22

    If you are sure that selectedOption of the constructor Filter(T selectedOption) is not null. You can use reflection. Like this.

    public class Filter {
        private List availableOptions = new ArrayList();
        private T selectedOption;
    
        public Filter(T selectedOption) {
            this.selectedOption = selectedOption;
            for (T option : this.selectedOption.getClass().getEnumConstants()) {  // INVALID CODE
                availableOptions.add(option);
            }
        }
    }

    Hope this helps.

提交回复
热议问题