Java Tutorial/Language/Standard Annotations

Материал из Java эксперт
Версия от 05:06, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A demo for SuppressWarnings: unchecked and fallthrough warnings

Uses the SuppressWarnings annotation type to prevent the compiler from issuing unchecked and fallthrough warnings



import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
@SuppressWarnings (value={"unchecked", "serial"})
public class SuppressWarningsTest implements Serializable {
    public void openFile () {
        ArrayList a = new ArrayList ();
        File file = new File ("X:/java/doc.txt");
    }
}





Documented

  1. Documented is a marker annotation type used to annotate the declaration of an annotation type so that instances of the annotation type will be included in the documentation.
  2. Override annotation type is not annotated using Documented.
  3. Deprecated annotation type is annotated @Documented.


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);
  }
}





Inherited

  1. Use Inherited to annotate an annotation type, any instance of the annotation type will be inherited.
  2. Use Inherited to annotate a class, the annotation will be inherited by any subclass of the annotated class. If the user queries the annotation type on a class declaration, and the class declaration has no annotation of this type, then the class"s parent class will automatically be queried for the annotation type. This process will be repeated until an annotation of this type is found or the root class is reached.


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());
    }
  }
}





Retention

  1. @Retention indicates how long annotations whose annotated types are annotated @Retention are to be retained.
  2. The value of @Retention can be one of the members of the java.lang.annotation.RetentionPolicy enum:
  1. SOURCE. Annotations are to be discarded by the Java compiler.
  2. CLASS. Annotations are to be recorded in the class file but not be retained by the JVM. This is the default value.
  3. RUNTIME. Annotations are to be retained by the JVM so you can query them using reflection.



@Retention(value=SOURCE)
public @interface SuppressWarnings





Standard Annotations: Deprecated

Deprecated is a marker annotation type that can be applied to a method or a type (class/interface) to indicate that the method or type is deprecated. Deprecating a method:



public class DeprecatedTest {
  @Deprecated
  public void serve() {
  }
}





Standard Annotations: Override

Override is a marker annotation type that can be applied to a method to indicate to the compiler that the method overrides a method in a superclass. This annotation type guards the programmer against making a mistake when overriding a method. For example, consider this class Parent:



class Parent {
    public float calculate (float a, float b) {
        return a * b;
    }
}
Whenever you want to override a method, declare the Override annotation type before the method:
public class Child extends Parent {
    @Override
    public int calculate (int a, int b) {
        return (a + 1) * b;
    }
}





Standard Annotations: SuppressWarnings

SuppressWarnings is used to suppress compiler warnings. You can apply @SuppressWarnings to types, constructors, methods, fields, parameters, and local variables.

The following are valid parameters to @SuppressWarnings:

  1. unchecked. Give more detail for unchecked conversion.
  2. path. Warn about nonexistent path (classpath, sourcepath, etc) directories.
  3. serial. Warn about missing serialVersionUID definitions on serializable classes.
  4. finally. Warn about finally clauses that cannot complete normally.
  5. fallthrough. Check switch blocks for fall-through cases.



switch (i) {
      case 1:
          System.out.println("1");
          break;
      case 2:
          System.out.println ("2");
          // falling through
      case 3:
          System.out.println ("3");
      }





Standard Meta-Annotations

  1. Meta annotations are annotations that are applied to annotations.
  2. There are four meta-annotation types: Documented, Inherited, Retention, and Target.
  3. All the four are part of the java.lang.annotation package.


Target

Target indicates which program element(s) can be annotated using instances of the annotated annotation type. The value of Target is one of the members of the java.lang.annotation.ElementType enum:

  1. ANNOTATION_TYPE. The annotated annotation type can be used to annotate annotation type declaration.
  2. CONSTRUCTOR. The annotated annotation type can be used to annotate constructor declaration.
  3. FIELD. The annotated annotation type can be used to annotate field declaration.
  4. LOCAL_VARIABLE. The annotated annotation type can be used to annotate local variable declaration.
  5. METHOD. The annotated annotation type can be used to annotate method declaration.
  6. PACKAGE. The annotated annotation type can be used to annotate package declarations.
  7. PARAMETER. The annotated annotation type can be used to annotate parameter declarations.
  8. TYPE. The annotated annotation type can be used to annotate type declarations.



@Target(value=METHOD)



You can have multiple values in the Target annotation.

@Target(value={TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})


The Built-In Annotations

  1. Java defines seven built-in annotations.
  2. Four are imported from java.lang.annotation: @Retention, @Documented, @Target, and @Inherited.
  3. Three, @Override, @Deprecated, and @SuppressWarnings, are included in java.lang.


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);
    }
}