Skip to main content

@nnotation type or type @nnotation

Posted by forax on March 18, 2007 at 7:42 AM PDT

The purpose of JSR 308 is to allow to
define annotation on types.


Currently, the JLS 3 only allows to annotate
language elements than accept modifiers so
it's not possible to annotate types.

Why allowing this is a good idea ?

There is real interest to allow annotation on Java types,
it enables to write safer code by performing
static source code analysis. Imagine annotations like:

  1. JetBrain's IDEA @NonNull, @Nullable
    to avoid NullPointerException and helps database mapper

  2. @Scoped to denote objects allocated in scoped memory of
    RTSJ

  3. Java Concurrent In Practice @Immutable or @ThreadSafe that allows to write
    safer code in a multi-threaded environment.

If you want to see more examples, the
current draft of the spec is available
here.

There are two possible syntax, the first one is to allow
annotation of type at the left of the type like
any other Java annotations. But it introduce an ambiguity
because a reader doesn't see clearly if an annotation belong to
a variable, a method etc. or its type.
In the following sample, @NonNull refers to String
and @Column refers to name.

  @Local
  class MyBean {
      @NonNull @Column(name="_NAME") String name;
      @Deprecated @NonNull Dimension getSize() { ... }
  }

The second one is to allow annotation on type at the
right of a type, in that case there is no ambiguity.

  @Local
  class MyBean {
      @Column(name="_NAME") String @NonNull name;
      @Deprecated Dimension @NonNull getSize() { ... }
  }

The JSR308 expert group seems to think that the first syntax is
better, more Java-like even if it introduce an ambiguity.


I am not totally convinced.

What do you think ?

Cheers, Rémi

Related Topics >>