and then make your code carefully treat Optional.NULL as if it were really null. the default value of an element must be a non-null constant expression. Public static final NULL = "THIS IS A SPECIAL NULL VALUE - DO NOT USE" In an annotation, an optional element is specified with the default modifier. The only thing you can do is workaround it, like this: When it sees '' + E.a, it uses E.a.toString(). The reason why 'a'+'b' and '' + 1 work is that the compiler is smart enough to generate the constants at compile time. It looks like it should be, but the compiler cant figure that out. You can never pass null as a Java annotation parameter value, because, uh, null isn't a ConstantExpression. If users can combine the allowed constants with a flag (such as, &, , and so on), you can define an annotation with a flag attribute to check whether a. The problem is that youre smarter than the compiler :-) E.a is a constant, but E.a.toString() is not. Notice anything missing? That's right, null. "The integer " + Long.MAX_VALUE + " is mighty big." JSR-175, which defined annotations for Java 5, just says "If member type is a primitive type or String, the ConditionalExpression must be a constant expression ( JLS 15.28)." JLS 15.28, in turn, says that constant expressions can be, for example, any of these: It is because arrays elements can be changed at runtime (Info.AB0 'c' ) while the annotation values are constant after compile time. Why is this? The specifications are opaque. javac says "attribute value must be constant " Eclipse says "The value for annotation attribute Optional.value must be a constant expression." In fact, it's not that surprising, because even if you didn't set a default value, writing this would also be illegal (same the error is saying is that you can't set a Java annotation parameter to null. Suppose you want to write a Java annotation that has a parameter value, but you want its default value to be null. I don't update here often enough, but here's a tidbit I wish I'd found on Google earlier.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |