I'm trying to add a default method for some of my enums using an interface with default method. The method should check if enum is in array(varargs) of enum values.
"Possible heap pollution from parameterized vararg type", but it's not in case of enum, cause it's final, right?"Unchecked cast: BaseEnum<E> to E" (and "Suspicious call" warning witout cast). It also would be safe until I pass right type parameter when implementing my interface.
Here is my example code:public interface BaseEnum<E extends Enum<E>> {
@SuppressWarnings("unchecked")
default boolean in(E ... statuses){
return Arrays.asList(statuses)
.contains((E) this);
}
}
public enum Transport implements BaseEnum<Transport> {
CAR, BUS, PLANE
}
public enum Fruit implements BaseEnum<Fruit> {
APPLE, CHERRY, LEMON
}
With this implementations everything looks safe. But how can I prevent something like this?(By 'prevent' I mean some code restrictions)
public enum Transport implements BaseEnum<Fruit> {
CAR, BUS, PLANE
}
I've looked at new Java 15 sealed feature, but seems its not the case. Is there any cleaner solution?
There is no need to create an interface for such an operation. The EnumSet class serves this purpose:
Fruit fruit = ...;
boolean match = EnumSet.of(Fruit.APPLE, Fruit.CHERRY).contains(fruit);
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