4

Eclipse keeps giving me the error:

The value for annotation attribute Min.value must be a constant expression

But I am most definitely giving the annotation a constant.

private static final int MIN_YEAR = Calendar.getInstance().get(Calendar.YEAR) - 1;

@Min(MIN_YEAR)

If I change it to be

private static final int MIN_YEAR = 2013;

It's perfectly happy, but I shouldn't have to do that. Does anyone know why or how my MIN_YEAR constant isn't considered a constant if it's declared with an evaluated expression instead of a plain number?

CorayThan
  • 17,174
  • 28
  • 113
  • 161
  • What is @Min from? What library? – Daniel Kaplan May 24 '13 at 21:47
  • import javax.validation.constraints.Min; – CorayThan May 24 '13 at 21:48
  • -1 since the first hit on googling your question is a duplicate. Please research before posting. If I am wrong and this does not answer your question, then you should have explained that you researched it, and explain why this does not fit your needs. http://stackoverflow.com/questions/2469473/variable-field-in-a-constraint-annotation – djechlin May 24 '13 at 21:49
  • 1
    @djechlin I found that and read it. It does not answer my question. My question is about why there is a difference between the way the two constants are declared, not how to create an annotation that allows non-constants. – CorayThan May 24 '13 at 21:53
  • Okay, a little more subtle. Answered here for instance: http://stackoverflow.com/questions/3827393/java-switch-statement-constant-expression-required-but-it-is-constant – djechlin May 24 '13 at 21:56

1 Answers1

9

The expression

private static final int MIN_YEAR = Calendar.getInstance().get(Calendar.YEAR) - 1;

will be determined only in run-time, but

private static final int MIN_YEAR = 2013;

is determined in compilation time, so it's allowed since the values in the annotations should be resolved at compilation time and not runtime.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • 2
    I suppose if the annotation runs at compile time that makes sense. I think that Eclipse's error message is somewhat misleading, though, since it says the problem is that it's not a `constant expression`, which both are. They just aren't both compile-time constant expressions, which is a little different. – CorayThan May 24 '13 at 21:58