注解
注解(Annotation):对程序的解释,但是和注释(comment)的区别是可以被编译器读取
1.常用内置注解:
@Override:用于方法重写,被重写的方法必须被声明在父类或Object中
@Deprecated:废弃一个方法,表示可以使用但是不推荐使用,该注解已经被淘汰,知道就行
@SuppressWarning:抑制警告,一般不用,除非看见警告实在是太烦了
看一下这个注解的源码:
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.SOURCE) public @interface SuppressWarnings { /** * The set of warnings that are to be suppressed by the compiler in the * annotated element. Duplicate names are permitted. The second and * successive occurrences of a name are ignored. The presence of * unrecognized warning names is <i>not</i> an error: Compilers must * ignore any warning names they do not recognize. They are, however, * free to emit a warning if an annotation contains an unrecognized * warning name. * * <p> The string {@code "unchecked"} is used to suppress * unchecked warnings. Compiler vendors should document the * additional warning names they support in conjunction with this * annotation type. They are encouraged to cooperate to ensure * that the same names work across multiple compilers. * @return the set of warnings to be suppressed */ String[] value(); }
能看到它是需要参数的(String[] value();不是方法是参数),一般参数写all
@SuppressWarnings("all")
public static void test2(){
System.out.println("不推荐");
}
2.元注解:负责注解其他注解,有@Target、@Retention、@Documented、@Inherited,最重要的是前两个
@Target:描述注解适用范围,源码如下:
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Target { /** * Returns an array of the kinds of elements an annotation type * can be applied to. * @return an array of the kinds of elements an annotation type * can be applied to */ ElementType[] value(); }
可以看到有ElementType类型的参数,再看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:表示注解的声明周期,因为RUNTIME>CLASS>SOURCE,所以参数一般写RUNTIME就行
@Documented:表示是否将注解生成在JAVAdoc中
@Inherited:子类可以继承父类注解
3.自定义一个注解
public class Annotationtest {
@MyAnnotation(name = "Bob",age = 18)
public static void main(String[] args){
System.out.println("hello world");
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
String name(); //用方法证明注解的参数,方法名就是参数名,方法的返回类型就是参数类型
int age();
}
}
浙公网安备 33010602011771号