Skip to main content

Proposed Annotations Enhancements

Posted by eitan on February 15, 2006 at 3:27 PM PST

I think these should make for a nice extension to the existing Java 5
Annotation API:

  1. From an Annotation, one should be able to navigate back to the programming element that it annotates.

    For example, a method annotation clearly marked with a Target
    of ElementType.METHOD cannot say getAnnotatedElement().getName(),

    There are two problems here. The first is the lack of the
    getAnnotatedElement() method
    The second is the fact that an AnnotatedElement is too primitive
    of an interface. You cannot actually invoke getName() on an
    annotated element. I feel that there should exist a basic
    ProgrammingElement implemented by or extended by all annotated
    elements.

  2. The default value for an annotated element should not be restricted
    to a constant expression. Instead, the value should be a code block.

    For example, let's assume that I want to annotate methods to
    give them a caption. By default, the caption should be some
    kind of derivation from the method name it is bound to.

    That is,

    class MyClass
    {
      @MyMethodAt(caption="The X Method")
      public void method x()
      {
        // ..
      }
    }


    and


    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface MyMethodAt
    {
      public String caption()
         default
         {
           return getAnnotatedElement().name();  // see [1]
         }
    }

    As far as I know, this is currently not possible.

* Entry cross-posted on my personal weblog

Related Topics >>