注解是在Java SE5中引入的,Java内置了三种注解:
@Override:子类重写父类方法时用。
@Deprecated:不赞成使用该元素(在Android中经常能看到某些类或方法Deprecated了)。
要注意@Deprecated与@deprecated的区别,@deprecated是为了生成文档的需要,具体如下所示:
/**
* @deprecated 该方法不建议使用
*/
@Deprecated
public void method() {
}
@SuppressWarnings:你觉得编译器的某些警告是没必要的,就可以用它了,不过它需要需要添加一个参数,我们下面看个用的比较多的unchecked:
@SuppressWarnings("unchecked")
public void method() {
List list = new ArrayList<>();
list.add("qwe");
}
下面我们来看下怎么自定义注解。
先看个最简单的,没有一个元素,被称为标记注解:
@MyAnnotation
public void method() {
}
@interface MyAnnotation {
}
下面看下带元素的注解:
@MyAnnotation(m = 5.6, m2 = "dsac")
public void method() {
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
double m();
String m2();
int m3() default 3;
}
大家有没有注意到上面的@Target和@Retention,它们叫元注解,相当于注解的注解,另两个是@Documented和@Inherited,具体含义如下:
@Target:限定注解可以修饰元素的种类,如果不加,注解既可以修饰类,也可以修饰变量,方法。上面的代码中我们限定了注解只能修饰方法。其中ElementType是个枚举类,源代码如下:
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}
@Retention:将注解分为三级。
SOURCE级,注解只存在源码中,会被编译器丢弃,如@Override,@SuppressWarnings之类的,比如Android中的注解式框架Dagger用的就是这个级别的注解。
CLASS级,注解存在于源码,字节码中,会被VM丢弃。
RUNTIME级:注解存在于源码,字节码,VM中,可用于运行时反射获取信息。
其中RetentionPolicy也是个枚举类,源代码如下:
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
@Documented:被修饰的注解会生成到Javadocs中,具体用javadoc命令生成看下就行了。
@Inherited:允许子类去继承父类的注解,具体看下面的例子,
package com.company;
import java.lang.annotation.*;
import java.util.Arrays;
public class Test4 {
public static void main(String[] args) {
A b = new B();
System.out.println(Arrays.toString(b.getClass().getAnnotations()));
}
}
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@interface MyInheritedAnnotation {
}
@Retention(RetentionPolicy.RUNTIME)
@interface MyUnInheritedAnnotation {
}
@MyInheritedAnnotation
@MyUnInheritedAnnotation
class A {
}
class B extends A {
}
输出为:
[@com.company.MyInheritedAnnotation()]