JEP proposal: Generic/Interfaced Enums as annotation attributes
Marc Miranda
marc.miranda84 at gmail.com
Wed Feb 16 00:26:59 UTC 2022
But you need to know the type beforehand, it cannot be a generic/interfaced
enum
Imagine you are designing an API and you want to let the user to specify
the Quality, but you don't want to impose him the particular enum so he can
add behaviour (implementing the quality).
In this case, you would like to define your Quality annotation so it
accepts any enum that implements a isEnoughQuality()
On the API side:
******************
@interface Quality {
Enum<Qualititable> value();
}
interface Qualititable {
boolean isEnoughQuality();
}
On the Client User Side:
****************************
@RequiredArgsConstructor
public enum MyCustomQualities implement Qualiitiable {
MY_CUSTOM_LOW_QUALITY(() -> false),
MY_CUSTOM_MEDIUM_QUALITY(() -> RandomUtils.getBoolean()),
MY_CUSTOM_HIGH_QUALITY(() -> true);
private final Supplier<Boolean> qualityEvaluator;
@Override
public isEnoughQuality() {
return qualityEvaluator.get();
}
}
Then you could use it like
@Quality(MyCustomQualities.LOW)
public void class Test {
(...)
}
El mar, 15 feb 2022 a las 23:19, Alex Buckley (<alex.buckley at oracle.com>)
escribió:
> On 2/15/2022 2:04 PM, Marc Miranda wrote:
> > I am not sure we are talking of the same use case.
> > In my case I am fine with non-generic enums, it is just about letting
> > annotation attributes pass an enum reference
>
> But an annotation can already have enum-typed elements. Here's an
> example from JLS 9.6.1:
>
> @interface Quality {
> enum Level { BAD, INDIFFERENT, GOOD }
> Level value();
> }
>
> @Quality(Quality.Level.BAD) public class Foo {}
>
> Alex
>
More information about the amber-dev
mailing list