Kaz Wolfe
Kaz Wolfe

Reputation: 438

Importing values from one Enum to another?

Right now, I have two Enums that need to have synchronized values only, and they are present in separate projects. I need to find some way to grab the values from one enum (Enum1) and import them into (Enum2).

What Enum1.java looks like:

package com.example.hello;

import com.example.foo.SomeClass;

public enum Enum1 {
     A(1), B(2), C(3), D(4);

     integer i;

     Enum1(int ii) {
         this.i = ii;
     }

     public static int getValue(Enum1 e) {
         return e.i;
     }

     public int doSomething() {
         return SomeClass.doThings(i);
     }
}

Meanwhile, Enum2.java (in a different project) currently looks like this:

package com.example.world;

import com.example.bar.SomeOtherClass;

import static com.example.hello.Enum1.*;

public enum Enum2 {
    // Enums *should* be imported from Enum1

    integer i;

    Enum2(int ii) {
        this.i = ii;
    }

    public int doSomethingElse() {
        return SomeOtherClass.doSomethingElse(i);
    }
}

Of course, this isn't working, because the values are not being carried across the gap.

The same reasoning would just be to use Enum1 in my code, but the functions on the Enums between the two projects needs to be completely different.

Is what I'm trying to do even possible? If so, how can I accomplish it in a (relatively) sane way?


For context, these two programs use these enums for a permission model. The system checks if a user is at or higher than the minimum required permission level, which could be something like Enum1.B. The problem is that Enum1 depends on a class that I cannot import into the project that contains Enum2, because it would be a complete waste to have to bundle a Java dependency with Enum2's project, especially if that project would never be realistically used for any reason.

Eventually, we're going to migrate over to a much more sane permission model where this entire system will be unnecessary, but we need something to work in the meantime, hence the need for a solution (or absolutely filthy hack) of some sort, just to get it working for now.

Upvotes: 4

Views: 289

Answers (1)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299138

I'd solve this through code generation. Somewhere in your build process of the project containing Enum2, read the Enum1 and create the Enum2 in a generated-source folder. All major build systems and IDEs do a good job at supporting generated code.

And for the actual code generation, you basically have 3 options:

  • Template-based, using a template framework like Velocity or Moustache
  • AST-based, using a code generator framework like JCodeModel
  • Do-it-yourself with good old string concatenation

I have an example project from a conference talk of mine, where I show how to integrate JCodeModel with a Maven build using Groovy. You can use it as a starting point.

Upvotes: 1

Related Questions