5

The following code works fine, where PROCESS_UPDATES is a constant.

    public static final String PROCESS_UPDATES = "ProcessUpdates";
    public static final String PROCESS_UPDATES = "ProcessSnapshots";
    // etc....

    @Produce(uri = "seda:" + MyClass.PROCESS_UPDATES)
    protected ProducerTemplate processUpdatesTemplate;

However to avoid a billion constant strings all over the place, I was experimenting with an enum design pattern.

    public enum Route { ProcessUpdates, ProcessSnapshots }

In most circumstances, I can write "seda:" + Route.ProcessSnapshots and it looks much neater.

However my trusty test code now fails, because the uri in the annotation must be constant.

    @Produce(uri = "seda:" + MyClass.Route.ProcessUpdates)    // compiler error
    protected ProducerTemplate processUpdatesTemplate;

Error: Attribute value must be constant.

The thing is, that Route.ProcessUpdates.toString() kind of "is" a constant, but the compiler doesn't see it that way.

I head a read about constants and annotations but I didn't see any answer.

So is there a nice way to construct a constant String from an enum at compile-time in java?

Thanks for any tips. vikingsteve

Community
  • 1
  • 1
vikingsteve
  • 38,481
  • 23
  • 112
  • 156
  • This posting might be of some use (String Literals in Java Enums): http://stackoverflow.com/questions/6667243/using-enum-values-as-string-literals – CodeChimp Dec 10 '13 at 14:37
  • Thanks, however none of the solutions there offer a "constant" value, as far as I can see, e.g. `MyClass.Route.ProcessSnapshots.name()` is not a constant (still get the error) – vikingsteve Dec 10 '13 at 14:49
  • There is no way to make an Enum a "constant". However, you can add the ability to turn an Enum into a String value, which could be made `final`. I think this is a better approach than the old `public static final` as it's more "portable", but that's only my opinion. – CodeChimp Dec 10 '13 at 15:02
  • @CodeChimp do you mean via a string argument to the enum constructor? Otherwise could you please elaborate. – vikingsteve Dec 10 '13 at 17:26
  • 1
    From your example, you are trying to concatenate a String using a constant. You could use the process in the linked post, creating an entry for `PROCESS_UPDATES("ProcessUpdates")` and `PROCESS_SNAPSHOTS("ProcessSnapshots")`, which sets some variable (in the example they use `name`, but it can be called whatever), then use the same overwritten `toString()` in the example. Then you would have an Enum that would toString to the one you wanted. – CodeChimp Dec 10 '13 at 20:36

1 Answers1

6

I didn't find a solution to this.

As far as I can see, it's not possible.

I needed to use string constants... public static final String XYZ = "Xyz"; - etc.

vikingsteve
  • 38,481
  • 23
  • 112
  • 156