Are there any downsides if we add Enum.name() to the list of constant expressions in the JLS?

Archie Cobbs archie.cobbs at gmail.com
Thu Oct 17 14:35:25 UTC 2024


On Wed, Oct 16, 2024 at 10:33 PM David Alayachew <davidalayachew at gmail.com>
wrote:

> As for the upsides, my personal use case is that I plan to use this for
> annotations. There's a couple of benefits, like grouping relevant pieces of
> information and methods together under the same enum value. Using
> valueOf(), I can derive a lot of information back from it, allowing me to
> add a whole bunch of information with a single source of truth. That has
> been the cause of a lot of bugs for me lately, and the only way to achieve
> something similar is to do something like nested classes or fake an enum.
> Why not just use the real thing?
>
Apologies, but I'm not completely understanding what you mean here.
Annotations already support enum-valued properties, so what new capability
would this change add?

While we're on the topic of what you can put in an annotation, I guess I'll
throw this idea out there... (previously I was too scared :)

Idea: What about allowing lambda values for Class-valued annotation
properties when the Class is a functional interface?

Example:

public @interface GenericStringConstraint {
    Predicate<String> checker();
    Function<String, String> errorGenerator() default s ->
String.format("Invalid value \"%s\"", s);
}

public class Person {

    @GenericStringConstraint(checker = s -> !s.isEmpty() &&
Character.isUpperCase(s.charAt(0)))
    public String getName() {
        ... // name must start with uppercase letter
    }
}

-Archie

-- 
Archie L. Cobbs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20241017/5b00e2ac/attachment-0001.htm>


More information about the amber-dev mailing list