Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a less verbose way to retrieve non deprecated enum values?

See my code below. I have an enum where some values are marked deprecated. I need a Collection of all the values of the enum which are not deprecated. I managed to accomplish the task using reflection, but it looks too verbose to me. Is there a cleaner way to define the presence of the @Deprecated tag ?

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class DeprecatedEnumValues {

public enum MyEnum {
    AA,
    BB,
    @Deprecated CC,
    DD,
    @Deprecated EE,
}

public static void main(String[] args) {

    List<MyEnum> myNonDeprecatedEnumValues = new ArrayList<MyEnum>();

    for (Field field : MyEnum.class.getDeclaredFields()) {
        if (field.isEnumConstant() && !field.isAnnotationPresent(Deprecated.class)) {
            myNonDeprecatedEnumValues.add(MyEnum.valueOf(field.getName()));
        }
    }
    System.out.println(myNonDeprecatedEnumValues);
}
}
like image 423
jeroen_de_schutter Avatar asked Jan 17 '14 15:01

jeroen_de_schutter


2 Answers

Here is the most effective implementation to get the non-deprecated enums with using the static block and Java 8 streams.

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public enum MyEnum {
    AA,
    BB,
    @Deprecated
    CC,
    DD,
    @Deprecated
    EE;

    private static List<MyEnum> nonDeprecatedEnums;

    static {
        nonDeprecatedEnums = Arrays.stream(MyEnum.values()).filter(value -> {
            try {
                Field field = MyEnum.class.getField(value.name());
                return !field.isAnnotationPresent(Deprecated.class);
            } catch (NoSuchFieldException | SecurityException e) {
                return false;
            }
        }).collect(Collectors.toList());
    }

    /**
     * Retrieve enum values without the @Deprecated annotation
     */

    public static List<MyEnum> getNonDeprecatedEnums() {
        return nonDeprecatedEnums;
    }
}
like image 62
viren shah Avatar answered Dec 07 '22 23:12

viren shah


Here is a more concise solution using streams:

public enum MyEnum {
    AA,
    BB,
    @Deprecated CC,
    DD,
    @Deprecated EE,

    /**
     * Retrieve enum values without the @Deprecated annotation
     */
    public static List<MyEnum> nonDeprecatedValues() {
        return Arrays.stream(MyEnum.values()).filter(value -> {
            try {
                Field field = MyEnum.class.getField(value.name());
                return !field.isAnnotationPresent(Deprecated.class);
            } catch (NoSuchFieldException | SecurityException e) {
                return false;
            }
        }).collect(Collectors.toList());
    }
}
like image 43
mark.monteiro Avatar answered Dec 08 '22 00:12

mark.monteiro