MetadataDemo.java

Download MetadataDemo.java

Show with line numbers

// Demo of using annotations (metadata).  Prior to annotations,
// you could (and still can) mark things deprecated by using
// a JavaDoc comment.  Even though it is a comment, the compiler is
// required to honor the tag:     /** @deprecated */ item
// The new way is much better!
// To see deprecation details use "javac -deprecation".  To enable
// that and all other warnings too, use "javac -Xlint".
//
// You can define your own annotations, as shown below.
//
// Written 2/2009 by Wayne Pollock, Tampa Florida USA.

import java.awt.event.*;
import java.lang.annotation.*;

class Metadata
{
   @Deprecated public int value = 1;

   @Deprecated public void aMethod ()
   {
      System.out.println( "Old, deprecated method invoked!" );
   }

   public void aNewMethod ()  { /* ... */ }
}

// A second class is needed because it is not considered an error to invoke
// a deprecated method from elsewhere in that same class!

public class MetadataDemo
{
   public static void main ( String [] args )
   {
      Metadata md = new Metadata();
      md.aNewMethod();         // Okay
      md.aMethod();            // Compiler warning
      int sum = 2 + md.value;  // Compiler warning
   }

   @SuppressWarnings("deprecation")
   public static void noWarning ( Metadata md )
   {
      md.aMethod();          // No warning, it is suppressed!
   }
}


// Demo of using "Override" annotation for cause a compiler error:

// This class contains a typo with a lower-case "c" for "windowClosing":

class myWindowHandler extends WindowAdapter
{
   @Override public void windowclosing ( WindowEvent we ) { }
}


// Here's a marker annotation example:

@Documented
@interface UglyCode {}

// and here's how it might be used:

class Foo {
   @UglyCode
   void aMethod ( int i, int[] list, int[] array ) {
      list[i++] += i++ * array[++i];
   }
}

// Here is a definition of my own annotation type, to label code
// with the bug numbers that caused the code to be updated:
// (From "The Java Programming Language" 4th Ed, page 392.)
// Note the name "value" should not be changed, or the short-cut usage doesn't
// work!

@interface BugsFixed
{
   String [] value();  // an array initialization, not a method
}

class SomeComplexClass
{
  public void someMethod()
  {
      // ...
      @BugsFixed( "12345" )
      int foo = 17;
      // ...
      @BugsFixed( value="56789" )  // Also works
      int bar = 22;
      // ...
      @BugsFixed( {"56789", "12543"} )  // Note array literal
      int baz = 3;
  }
}