MetadataDemo.java

Download MetadataDemo.java

 1: // Demo of using annotations (metadata).  Prior to annotations,
 2: // you could (and still can) mark things deprecated by using
 3: // a JavaDoc comment.  Even though it is a comment, the compiler
 4: // is required to honor the tag:     /** @deprecated */ item
 5: // The new way is much better!
 6: // To see deprecation details, use "javac -deprecation".  To
 7: // enable that and all other warnings too, use "javac -Xlint:all".
 8: //
 9: // You can define your own annotations, as shown below.
10: //
11: // Written 2/2014 by Wayne Pollock, Tampa Florida USA.
12: 
13: import java.awt.event.*;
14: import java.lang.annotation.*;
15: 
16: class Metadata {
17:    @Deprecated
18:    public int value = 1;
19: 
20:    @Deprecated
21:    public void aMethod () {
22:       System.out.println( "Old, deprecated method invoked!" );
23:    }
24: 
25:    public void aNewMethod ()  {
26:       /* ... */
27:    }
28: }
29: 
30: // A second class is needed because it is not considered an error
31: // to invoke a deprecated method from elsewhere in that same class!
32: public class MetadataDemo {
33:    public static void main ( String [] args ) {
34:       Metadata md = new Metadata();
35:       md.aNewMethod();         // Okay
36:       md.aMethod();            // Compiler warning
37:       int sum = 2 + md.value;  // Compiler warning
38:    }
39: 
40:    @SuppressWarnings( "deprecation" )
41:    public static void noWarning ( Metadata md ) {
42:       md.aMethod();           // No warning, it is suppressed!
43:    }
44: }
45: 
46: // Demo of using "Override" annotation that will cause a compiler error
47: // (The method contains a typo: a lower-case "c" for "windowClosing"):
48: class myWindowHandler extends WindowAdapter {
49:    @Override
50:    public void windowclosing ( WindowEvent we ) { }
51: }
52: 
53: // Here's a marker annotation example:
54: @interface UglyCode {}
55: 
56: // And here's how it might be used:
57: 
58: class Foo {
59:    @UglyCode
60:    void aMethod ( int i, int[] list, int[] array ) {
61:       list[i++] += i++ * array[++i];
62:    }
63: }
64: 
65: // Here is a definition of a new annotation type, to label code
66: // with the bug numbers that caused the code to be updated:
67: // (From "The Java Programming Language" 4th Ed, page 392.)
68: // Note the name "value" should not be changed, or the short-cut
69: // usage doesn't work!
70: @Documented
71: @interface BugsFixed {
72:    String [] value ();  // An array initialization, not a method.
73: }
74: 
75: class SomeComplexClass {
76:   @BugsFixed( "12345" )
77:   public void someMethod() {
78:       // ...
79:       int foo = 17;
80:       // ...
81:       @BugsFixed( value="56789" )  // Also works.
82:       int bar = 22;
83:       // ...
84:       @BugsFixed( {"56789", "12543"} )  // Note the array literal.
85:       int baz = 3;
86:   }
87: }