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 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;
}
}
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With