/home/wpollock1/public_html/AJava/MetadataDemo.java
// 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:all".
//
// You can define your own annotations, as shown below.
//
// Written 2/2014 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 that will cause a compiler error
// (The method contains a typo: a lower-case "c" for "windowClosing"):
class myWindowHandler extends WindowAdapter {
@Override
public void windowclosing ( WindowEvent we ) { }
}
// Here's a marker annotation example:
@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 a new 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!
@Documented
@interface BugsFixed {
String [] value (); // An array initialization, not a method.
}
class SomeComplexClass {
@BugsFixed( "12345" )
public void someMethod() {
// ...
int foo = 17;
// ...
@BugsFixed( value="56789" ) // Also works.
int bar = 22;
// ...
@BugsFixed( {"56789", "12543"} ) // Note the array literal.
int baz = 3;
}
}