[JSR308] Use of @Target meta-annotation
Maxim Kizub
mkizub at gmail.com
Sat May 19 13:42:53 EDT 2007
Hello.
First, I have a question.
Do we have any example, where an annotation is applicable only to the
type of a declaration, but not to the declared node itself?
I guess - there are no such examples. For the following reason - the
type of the declared entity is also a kind of annotation (meta-data).
The type is not really needed, it's a constraint or a hint. Many
languages use type inferring and omit types declaration in many places.
A property (constraint or hint) for the type is always the same property
of the declared element.
Ergo.
@Target(TYPE) is mostly meaningless, because it will mean that the
annotation may be used for fields, methods, variables - mostly
all elements. The only rare case for a separate @Target(TYPE) are
expressions, i.e. when the annotation may be declared on expressions,
but not on declarations. The best usage of @Target(TYPE) which I can
imagine - to mark those annotations which we want to
store in type signatures.
Also.
It's semantically the same to declare
@NotNull String s;
and
String<@NotNull> s;
and it's true for all type annotations. The only syntactical difference
are cases with multi-type ambiguous declarations, like
@Foo int i, iarr[]; // @Foo applies to 'int' , i.e. "Foo int &
int[@Foo]" or to declarations, i.e. "@Foo int & @Foo int[]" ?
@Foo Object o, oarr[];
If @Foo is something like @positive, then one would expect that we
declare "@positive int i" and "int[@positive] iarr".
But if @Foo is something like @Readonly, then one will be in doubt if we
declare "Array<Object<@Readonly>> oarr" or
"Array<@Readonly; Object> oarr" (read-only are elements of the array or
the reference to the array).
Usage of annotations in expressions also may require specification
outside of declaration, like
new List<@NonEmpty; String>("head", "tail");
Another possible usage are java extensions, like MultiJava, which uses
multi-type method formal parameters, like
boolean equals(String:Object value)
to specify separately dispatch type and method signature.
Finally, unambiguous simple syntax will be helpful for code generators,
which shell not think of how to generate
type annotations in different syntax positions.
For these cases, i.e. for ambiguous or auto-generated declarations or
for expressions, we need a per-type
annotation syntax.
For unambiguous declarations we may allow to use both @NotNull String s;
and String<@NotNull> s;
as equivalent constructs, and annotation processor shell take care of
it. The reason is simple - if we'll
change @Target from FIELD or LOCAL_VARIABLE to @Target(TYPE) - we don't
want the
programmer to change all declarations in the code which happen to use
this annotation.
More information about the JSR308
mailing list