RFR: Generate Java enums
Maurizio Cimadamore
mcimadamore at openjdk.org
Thu Jul 3 09:46:58 UTC 2025
On Fri, 20 Jun 2025 17:09:19 GMT, Vivek Narang <duke at openjdk.org> wrote:
> We are using jextract in our [cuVS Java](https://github.com/rapidsai/cuvs/tree/branch-25.08/java) project. As of now, jextract generates individual getter functions for the C enums. This results in code where it is difficult to disambiguate which getter functions are logically grouped together for a particular Enum. Additionally, given the lack of this capability, we also have to manually create and maintain Java enums for each enum in the C layer.
>
> In this PR, I wish to introduce an option to additionally generate Java enums by passing an optional flag `--generate-java-enums`. In case a Java user wishes to use bitwise operations on the enums, they can use the enum's `.ordinal()` method for this. The original static getter methods will still be generated as before.
>
> Example C enum:
>
> enum SIZE {
> S,
> M,
> L
> };
>
> Produces the following with jextract:
>
> private static final int S = (int)0L;
> public static int S() {
> return S;
> }
>
> private static final int M = (int)1L;
> public static int M() {
> return M;
> }
>
> private static final int L = (int)2L;
> public static int L() {
> return L;
> }
>
> With this feature enabled using the `--generate-java-enums` flag, the following enum is generated (in addition to the above):
>
> public enum Size {
> S(0),
> M(1),
> L(2);
>
> private final int value;
>
> private Size(int value) {;
> this.value = value;
> }
>
> public int getValue() {
> return this.value;
> }
> }
>
> This PR is created against the `jdk22` branch. I will rebase it to `master` branch if needed.
Another thing that came to mind: if we translate C enums as Java enums -- how is a native function accepting a C enum type translated? If we translate it as an int-accepting function (what we do now) then the Java enum constants cannot be used to call into native functions. If we translate it as a Java-enum-accepting function, then we would make these function stricter than their C counterparts.
-------------
PR Comment: https://git.openjdk.org/jextract/pull/284#issuecomment-3031606147
More information about the jextract-dev
mailing list