Java/Language Basics/Annotation — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 06:47, 1 июня 2010

A marker annotation.

 
import java.lang.annotation.*; 
import java.lang.reflect.*; 
 
@Retention(RetentionPolicy.RUNTIME)  
@interface MyMarker { } 
 
public class Marker { 
 
  // Annotate a method using a marker. 
  // Notice that no ( ) is needed. 
  @MyMarker 
  public static void myMeth() { 
    Marker ob = new Marker(); 
 
    try { 
      Method m = ob.getClass().getMethod("myMeth"); 
 
      // Determine if the annotation is present. 
      if(m.isAnnotationPresent(MyMarker.class)) 
        System.out.println("MyMarker is present.");  
 
    } catch (NoSuchMethodException exc) { 
       System.out.println("Method Not Found."); 
    } 
  } 
 
  public static void main(String args[]) { 
    myMeth(); 
  } 
}





An annotation type declaration.

 
/*
Java 2, v5.0 (Tiger) New Features
by Herbert Schildt
ISBN: 0072258543
Publisher: McGraw-Hill/Osborne, 2004
*/
import java.lang.annotation.*; 
import java.lang.reflect.*; 
 
@Retention(RetentionPolicy.RUNTIME)  
@interface MyAnno { 
  String str(); 
  int val(); 
} 
 
public class Meta { 
 
  // Annotate a method. 
  @MyAnno(str = "Annotation Example", val = 100) 
  public static void myMeth() { 
    Meta ob = new Meta(); 
 
    // Obtain the annotation for this method 
    // and display the values of the members. 
    try { 
      // First, get a Class object that represents 
      // this class. 
      Class c = ob.getClass(); 
 
      // Now, get a Method object that represents 
      // this method. 
      Method m = c.getMethod("myMeth"); 
 
      // Next, get the annotation for this class. 
      MyAnno anno = m.getAnnotation(MyAnno.class); 
  
      // Finally, display the values. 
      System.out.println(anno.str() + " " + anno.val()); 
    } catch (NoSuchMethodException exc) { 
       System.out.println("Method Not Found."); 
    } 
  } 
 
  public static void main(String args[]) { 
    myMeth(); 
  } 
}





An annotation type declaration 2.

 
/*
Java 2, v5.0 (Tiger) New Features
by Herbert Schildt
ISBN: 0072258543
Publisher: McGraw-Hill/Osborne, 2004
*/
import java.lang.annotation.*; 
import java.lang.reflect.*; 
 
@Retention(RetentionPolicy.RUNTIME)  
@interface MyAnno { 
  String str(); 
  int val(); 
} 
 
public class Meta1 { 
 
  // myMeth now has two arguments. 
  @MyAnno(str = "Two Parameters", val = 19) 
  public static void myMeth(String str, int i)  
  { 
    Meta1 ob = new Meta1(); 
 
    try { 
      Class c = ob.getClass(); 
 
      // Here, the parameter types are specified. 
      Method m = c.getMethod("myMeth", String.class, int.class); 
 
      MyAnno anno = m.getAnnotation(MyAnno.class); 
  
      System.out.println(anno.str() + " " + anno.val()); 
    } catch (NoSuchMethodException exc) { 
       System.out.println("Method Not Found."); 
    } 
  } 
 
  public static void main(String args[]) { 
    myMeth("test", 10); 
  } 
}





An annotation type declaration and include defaults.

 
import java.lang.annotation.*; 
import java.lang.reflect.*; 
 
@Retention(RetentionPolicy.RUNTIME)  
@interface MyAnno { 
  String str() default "Testing"; 
  int val() default 9000; 
} 
 
public class Meta3 { 
 
  // Annotate a method using the default values. 
  @MyAnno() 
  public static void myMeth() { 
    Meta3 ob = new Meta3(); 
 
    // Obtain the annotation for this method 
    // and display the values of the members. 
    try { 
      Class c = ob.getClass(); 
 
      Method m = c.getMethod("myMeth"); 
 
      MyAnno anno = m.getAnnotation(MyAnno.class); 
  
      System.out.println(anno.str() + " " + anno.val()); 
    } catch (NoSuchMethodException exc) { 
       System.out.println("Method Not Found."); 
    } 
  } 
 
  public static void main(String args[]) { 
    myMeth(); 
  } 
}





Annotation Demo

 
public class StringUtility {
@TestParameters(testStage="Unit",
                testMethods="testConcat,testSubstring",
                testOutputType="screen",
                testOutput="")
    public String concat(String s1, String s2)
    {
        return(s1 + s2);
    }
    public String substring(String str, int start, int end)
    {
        return(str.substring(start, end));
    }
    public boolean testConcat()
    {
        String s1 = "test";
        String s2 = " 123";
        return(concat(s1,s2).equals("test 123"));
    }
    public boolean testSubstring()
    {
        String str = "The cat landed on its feet";
        return(substring(str, 4, 3).equals("cat"));
    }
}





Annotation Viewer

 
import com.sun.javadoc.*;
import java.lang.annotation.*;
public class AnnotationViewer {
    public static boolean start(RootDoc root)
    {
        ClassDoc[] classes = root.classes();
        for (ClassDoc cls : classes) {
            showAnnotations(cls);
        }
        return(true);
    }
    static void showAnnotations(ClassDoc cls)
    {
        System.out.println("Annotations for class [" + cls + "]");
        process(cls.annotations());
        System.out.println();
        for(MethodDoc m : cls.methods()) {
            System.out.println("Annotations for method [" + m + "]");
            process(m.annotations());
            System.out.println();
        }
    }
    static void process(AnnotationDesc[] anns)
    {
        for (AnnotationDesc ad : anns) {
            AnnotationDesc.ElementValuePair evp[] = ad.elementValues();
            for(AnnotationDesc.ElementValuePair e : evp) {
                System.out.println("  NAME: " + e.element() + ", VALUE=" + e.value());
            }
        }
    }
}





A single member annotation.

 
import java.lang.annotation.*; 
import java.lang.reflect.*; 
 
@Retention(RetentionPolicy.RUNTIME)  
@interface MySingle { 
  int value(); // this variable name must be value 
} 
 
public class Single { 
 
  // Annotate a method using a marker. 
  @MySingle(100) 
  public static void myMeth() { 
    Single ob = new Single(); 
 
    try { 
      Method m = ob.getClass().getMethod("myMeth"); 
 
      MySingle anno = m.getAnnotation(MySingle.class); 
 
      System.out.println(anno.value()); // displays 100 
 
    } catch (NoSuchMethodException exc) { 
       System.out.println("Method Not Found."); 
    } 
  } 
 
  public static void main(String args[]) { 
    myMeth(); 
  } 
}





How do I mark method as deprecated?

 
import java.util.Calendar;
import java.util.Date;
public class Main {
  public static void main(String[] args) {
    getDate();
    getMonthFromDate();
  }
  /**
   * Get current system date.
   * 
   * @return current system date.
   * @deprecated This method will removed in the near future.
   */
  @Deprecated
  public static Date getDate() {
    return new Date();
  }
  public static int getMonthFromDate() {
    return Calendar.getInstance().get(Calendar.MONTH);
  }
}





Insert an annotation to suppress warning

 
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
  @SuppressWarnings("unchecked")
  public static void main(String[] args) {
    ArrayList data = new ArrayList();
    data.add("hello");
    data.add("world");
    Iterator it = data.iterator();
    while (it.hasNext()) {
      System.out.println(it.next());
    }
  }
}





Java Annotation: Annotation and Reflection

 
/*
License for Java 1.5 "Tiger": A Developer"s Notebook
     (O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.AnnotatedElement;
import java.lang.annotation.Annotation;
import java.util.Date;
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public class ReflectionTester {
  public ReflectionTester() {
  }
  public void testAnnotationPresent(PrintStream out) throws IOException {
    Class c = Super.class;
    boolean inProgress = c.isAnnotationPresent(InProgress.class);
    if (inProgress) {
      out.println("Super is In Progress");
    } else {
      out.println("Super is not In Progress");
    }
  }
  public void testInheritedAnnotation(PrintStream out) throws IOException {
    Class c = Sub.class;
    boolean inProgress = c.isAnnotationPresent(InProgress.class);
    if (inProgress) {
      out.println("Sub is In Progress");
    } else {
      out.println("Sub is not In Progress");
    }
  }
  public void testGetAnnotation(PrintStream out) 
    throws IOException, NoSuchMethodException {
    Class c = AnnotationTester.class;
    AnnotatedElement element = c.getMethod("calculateInterest", 
                                  float.class, float.class);
    GroupTODO groupTodo = element.getAnnotation(GroupTODO.class);
    String assignedTo = groupTodo.assignedTo();
    out.println("TODO Item on Annotation Tester is assigned to: "" + 
        assignedTo + """);
  }
  public void printAnnotations(AnnotatedElement e, PrintStream out)
    throws IOException {
    out.printf("Printing annotations for "%s"%n%n", e.toString());
    Annotation[] annotations = e.getAnnotations();
    for (Annotation a : annotations) {
      out.printf("    * Annotation "%s" found%n", 
        a.annotationType().getName());
    }
  }
  public static void main(String[] args) {
    try {
      ReflectionTester tester = new ReflectionTester();
      tester.testAnnotationPresent(System.out);
      tester.testInheritedAnnotation(System.out);
      tester.testGetAnnotation(System.out);
      Class c = AnnotationTester.class;
      AnnotatedElement element = c.getMethod("calculateInterest", 
                                    float.class, float.class);      
      tester.printAnnotations(element, System.out);
    } catch (Exception e) {
      e.printStackTrace();
    } 
  }
}
class Sub extends Super {
  public void print(PrintStream out) throws IOException {
    out.println("Sub printing...");
  }
}
@InProgress class Super {
  public void print(PrintStream out) throws IOException {
    out.println("Super printing...");
  }
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@interface GroupTODO {
  public enum Severity { CRITICAL, IMPORTANT, TRIVIAL, DOCUMENTATION };
  Severity severity() default Severity.IMPORTANT;
  String item();
  String assignedTo();
  String dateAssigned();
}
/**
 * Marker annotation to indicate that a method or class
 *   is still in progress.
 */
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@interface InProgress { }





Java Annotation: Deprecated and hierarchy

 
/*
License for Java 1.5 "Tiger": A Developer"s Notebook
     (O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/

public class DeprecatedTester extends DeprecatedClass {
  public void doSomething() {
    // Overrides a deprecated method
  }
}
class DeprecatedClass {
  /**
   * This method has now been deprecated in favor of doSomethingElse()
   * @deprecated Use doSomethingElse() instead
   */
  @Deprecated public void doSomething() {
    // Really... do something...
  }
  public void doSomethingElse() {
    // Do something else (and presumably better)
  }
}





Java annotation: Super Sub Tester

 
/*
License for Java 1.5 "Tiger": A Developer"s Notebook
     (O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/
import java.io.*;
public class SuperSubTester {
  public static void main(String[] args) {
    try {
      Sub sub = new Sub();
      sub.print(System.out);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
class Sub extends Super {
  public void print(PrintStream out) throws IOException {
    out.println("Sub printing...");
  }
}
@InProgress class Super {
  public void print(PrintStream out) throws IOException {
    out.println("Super printing...");
  }
}





Java Annotation Tester

 
/*
License for Java 1.5 "Tiger": A Developer"s Notebook
     (O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class AnnotationTester {
  @InProgress
  @GroupTODO(
    severity=GroupTODO.Severity.CRITICAL,
    item="Figure out the amount of interest per month",
    assignedTo="Brett McLaughlin",
    dateAssigned="04-26-2004"
  )
  public void calculateInterest(float amount, float rate) {
    // Need to finish this method later
  }
}

/**
 * Marker annotation to indicate that a method or class
 *   is still in progress.
 */
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@interface InProgress { }


@Documented
@Retention(RetentionPolicy.RUNTIME)
@interface GroupTODO {
  public enum Severity { CRITICAL, IMPORTANT, TRIVIAL, DOCUMENTATION };
  Severity severity() default Severity.IMPORTANT;
  String item();
  String assignedTo();
  String dateAssigned();
}





Override Annotation Tester

 
/*
License for Java 1.5 "Tiger": A Developer"s Notebook
     (O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/
public class OverrideTester {
  public OverrideTester() { }
  @Override
  public String toString() {
    return super.toString() + " [OverrideTester Implementation]";
  }
  @Override
  public int hashCode() {
    return toString().hashCode();
  }
  /**
   * Uncomment to see @Override in action on a misspelled method
  @Override
  public int hasCode() {
    return toString().hashCode();
  }
  */
}





Show all annotations for a class and a method.

 
import java.lang.annotation.*; 
import java.lang.reflect.*; 
 
@Retention(RetentionPolicy.RUNTIME)  
@interface MyAnno { 
  String str(); 
  int val(); 
} 
 
@Retention(RetentionPolicy.RUNTIME)  
@interface What { 
  String description(); 
} 
 
@What(description = "An annotation test class") 
@MyAnno(str = "Meta2", val = 99) 
public class Meta2 { 
 
  @What(description = "An annotation test method") 
  @MyAnno(str = "Testing", val = 100) 
  public static void myMeth() { 
    Meta2 ob = new Meta2(); 
 
    try { 
      Annotation annos[] = ob.getClass().getAnnotations(); 
 
      // Display all annotations for Meta2. 
      System.out.println("All annotations for Meta2:"); 
      for(Annotation a : annos) 
        System.out.println(a); 
 
      System.out.println(); 
 
      // Display all annotations for myMeth. 
      Method m = ob.getClass( ).getMethod("myMeth"); 
      annos = m.getAnnotations();  
 
      System.out.println("All annotations for myMeth:"); 
      for(Annotation a : annos) 
        System.out.println(a); 
 
    } catch (NoSuchMethodException exc) { 
       System.out.println("Method Not Found."); 
    } 
  } 
 
  public static void main(String args[]) { 
    myMeth(); 
  } 
}





Simple annotation

 
/*
License for Java 1.5 "Tiger": A Developer"s Notebook
     (O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * Annotation type to indicate a task still needs to
 *   be completed.
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,
         ElementType.METHOD, 
         ElementType.CONSTRUCTOR, 
         ElementType.ANNOTATION_TYPE})
public @interface TODO { 
  String value();
}





Suppress warning in ANT script

 
<target name="compile">
       <javac srcdir="${src}" destdir="${bin}" 
              includeAntRuntime="no" 
              debug="${compile.debug}">
           <compilerarg value="-Xlint:unchecked"/>
       </javac>
</target>





SuppressWarnings Annotation Tester

 
/*
License for Java 1.5 "Tiger": A Developer"s Notebook
     (O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/
import java.util.ArrayList;
import java.util.List;
public class SuppressWarningsTester {
  /**
   * Normal pre-1.5 method body
   */
  @SuppressWarnings(value={"unchecked"})
  public void nonGenericsMethod() {
    List wordList = new ArrayList();
    wordList.add("foo");
  }
}





Use Override annotation

 
public class Main {
  private String field;
  private String attribute;
  @Override
  public int hashCode() {
    return field.hashCode() + attribute.hashCode();
  }
  @Override
  public String toString() {
    return field + " " + attribute;
  }
}





What is SuppressWarnings annotation?

 
import java.util.Date;
 
public class Main {
    @SuppressWarnings(value={"deprecation"})
    public static void main(String[] args) {
        Date date = new Date(2009, 9, 30);
 
        System.out.println("date = " + date);
    }
}