Java注解(Annotation)
一、什么是注解:
1.注解的作用:
不是程序本身,可以对程序作出解释(和注释作用一样);
可以被其他程序(例如编译器)读取
2.注解的格式:
以“@注释名”在代码中存在
3.注解在哪里使用:
可以在package、class、method、field等上面使用,相当于给他们添加了额外的辅助信息,可以通过反射机制编程实现对这些元数据的访问
4.基本知识:
①Annotation 的类型定义为@interface ,所有的Annotation 都会自动继承java.lang.Annotation接口,并且不能继承其他的类或者接口
②参数成员只能用public 或default两个访问权修饰
③参数成员只能用8种基本类型byte,short,char,int,long,float,double,boolean和String ,Enum,Class,annotations 等数据类型,以及这一些类型的数组。
④注解也可以没有定义成员,不过这样的注解就没有啥用,只起到标识作用
二、内置注解:
@Override
@Deprecated
@SuppressWarnings(“all”)
三、元注解:
@Retention @Target @Document @Inherited
四、自定义注解:
使用@interface
例子:
@SuppressWarnings("all")
public class AnnotationDemo {
@MyAnnotation2(value = {"1","2"}, age = 2)
private String dog;
@MyAnnotation("wuxia")
public void test() {
}
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
//注解的参数: 参数类型 + 参数名 ();
String value() default "";
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2 {
String[] value();
String name() default "";
int age();
int id() default -1;
String[] job() default{"平安养老险","上海申铁"};
}