Custom Annotations

Adding your own custom annotations to the library is relatively simple. All annotation processing is hanlded by an instance of the AnnotationSupport interface. The default implementation is provided by DefaultAnnotationSupport.

This class uses AnnotationProcessor instances to process each of the annotation types. The following example shows how to install a custom annotation processor.

   DefaultAnnotationSupport support = 
     (DefaultAnnotationSupport) GuiCommands.defaults().getAnnotationSupport();

   support.installProcessor(new MyAnnotationProcessor());

Processors must implement the AnnotationProcessor interface. The following example shows a brief example of an annotation and its processor.

   @Retention(RetentionPolicy.RUNTIME)
   @Target(ElementType.METHOD)
   public @interface
   MyAnnotation
   {
      /**
       * The id of the command.
       */
      String value();
   }

And the processor for the above annotation.

   public class MyAnnotationProcessor
   implements AnnotationProcessor<MyAnnotation>
   {
      /**
       * Gets the annotation class handled by this processor.
       *
       * @return the annotation class handled by this processor.
       */
      public Class<MyAnnotation> getAnnotation()
      {
         return MyAnnotation.class;
      }

      /**
       * Invoked to create the command defined by the annotations of
       * the class defined by {@link #getAnnotation()}.
       *
       * @param target the target object.
       * @param method the target method with the annotation.
       *
       * @return a new command instance that invokes the specified method 
       *  on the specified target object.
       */
      public Command
      createCommand(Object target, Method method)
      {
         // get the annotation from the method
         MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
         String id = annotation.value();

         // now create a command to invoke the method
         // on the specified target
         return ...;
      }
   }

Calls to GuiCommands.bindAnnotatedCommands(...) will now automatically process methods annotated with MyAnnotation.

   public class AnnotatedClass
   {
      @MyAnnotation("my-command")
      public void myMethod()
      {
         // do stuff
      }
   }


   AnnotatedClass annotatedClass = ...;
   CommandContainer container = ...;

   GuiCommands.bindAnnotatedCommands(container, annotatedClass);