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

java reflection get enum values
java get enum values from class
java reflection get enum from string
java enum
java reflection get enum name
getenumconstants
get all values of enum java
java reflection enum constructor

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);
}
}

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());
    }
}

Examining Enums (The Java™ Tutorials > The Reflection API , If an instance of an enum type is not available the only way to get a list of the possible values is to invoke Class.getEnumConstants() since it is impossible to� 11 Is there a less verbose way to retrieve non deprecated enum values? Jan 17 '14. 7 how to create mvc based application without using framework Aug 21 '13.

It's not that big of a difference but you could place your analysis into the enum itself so it's more convenient to use and the if-clause becomes simpler:

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 List<MyEnum> getNonDepricatedEnumValues(){
            List<MyEnum> myNonDeprecatedEnumValues = new ArrayList<MyEnum>();

            for (MyEnum enumValue : MyEnum.values())
                try {
                    Field field = MyEnum.class.getField(enumValue.name());                      
                    if (field.isAnnotationPresent(Deprecated.class))
                        continue;

                    myNonDeprecatedEnumValues.add(enumValue);                   
                } catch (NoSuchFieldException | SecurityException e) {}
                // both cannot occure here..

            return myNonDeprecatedEnumValues;
        }
    }

    public static void main(String[] args) {
        System.out.println(MyEnum.getNonDepricatedEnumValues());
    }
}

Move Enum mappings from @Mapping to an @ValueMapping , I'm often in the situation that I need to map String -> String Integer That would also remove the need of writing a mapping method that does that get call. I think of it a bit more, like this (perhaps a bit more rigid but less verbose). If the value is not of type {@code String}, the value will be converted by� 7 jQuery calculate sum of values in all text fields May 26 '16 7 Checking type parameter of a generic method in C# Nov 24 '17 5 Is there a less verbose way to retrieve non deprecated enum values?

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;
    }
}

PDSC Syntax, The Pegasus schema differs from Avro in the following ways: Avro default values for union types do not include the member discriminator. The named schemas with type “enum” also supports a symbolDocs attribute to provide common union with null pattern that is used to represent optional fields to be less verbose. Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

Deprecated List (Jenkins core 2.249 API), TODO: revisit tool update mechanism, as that should be de-centralized, too. In the mean time, please try not to use this method, and instead ping us to get this� Set to all for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1) op_type enum

Defining blocks, Try out some blocks live in the Playground to see how they work. parameters are detected; Using =type in the block string for shadow blocks is deprecated. blockId="array_pop" block="get and remove last value from %list" function pop(): Enums in TypeScript can be verbose, so sometimes it is desirable to compile a � It is possible for a single method to have deprecated and non-deprecated overloadings. It is possible for a non-deprecated property to hide or override a deprecated one, which removes deprecation. As developer of an API, it is your responsibility to deprecate overrides of a deprecated method, if in fact they should be deprecated.

Histogram Guidelines, This document gives the best practices on how to use histograms in code and how to the two histograms to get the total histogram, you're implicitly assuming those values Note this bullet point does not apply for enums logged with sparse histograms. have Note: this method of defining histogram enums is deprecated. A name declared non-deprecated may be redeclared deprecated. A name declared deprecated cannot be un-deprecated by redeclaring it without this attribute. [ edit ] Example

Comments
  • That doesn't look terribly verbose to me (for Java). I haven't worked a ton with reflection in Java, but that is how I would do it.
  • I would have used && instead of & but otherwise only using shorter names would make it shorter.
  • @PeterLawrey, thanks. My coding accuracy is a bit sloppy on friday afternoon ;-) I will edit the sample code.
  • For a moment I thought you had invented an AND-NOT operator &!
  • Nice, but I could not change the code of the Enum, because it was part of a library.
  • You can do the same in a method outside of the enum itself. Simply move the method into your own code.
  • Very Impressive