Annotation是JDK1.5后引入的新技术
不是程序本身,可以对程序做出解释(这一点跟注释(comment)没什么区别)
可以被其他程序读取(如编译器)
定义在java.lang.Override中,此注解只适合于修辞方法,表示一个方法打算重写超类中另一个方法声明
当一个类型或者类型成员使用@Deprecated修饰的话,编译器将不鼓励使用这个被标注的程序元素。
用来抑制编译时的警告信息
- package com.lixi;
-
- //下面三种注解都是内置注解
- //镇压警告,不推荐多使用
- @SuppressWarnings("all")
- public class Test01 {
- //重写的注解
- @Override
- public String toString() {
- return super.toString();
- }
-
- //不推荐程序员使用,
- @Deprecated
- public void test() {
- System.out.println("Deprecated");
- }
-
- public static void main(String[] args) {
- Test01 t = new Test01();
- t.test();
- }
- }
元注解的作用就是负责注解其他注解
简单来说就是被描述的注解可以用在什么地方
● ElementType.CONSTRUCTOR:用于描述构造器
● ElementType.FIELD:成员变量、对象、属性(包括enum实例)
● ElementType.LOCAL_VARIABLE:用于描述局部变量
● ElementType.METHOD:用于描述方法
● ElementType.PACKAGE:用于描述包
● ElementType.PARAMETER:用于描述参数
● ElementType.TYPE:用于描述类、接口(包括注解类型) 或enum声明
用于描述注解的生命周期
● RetentionPolicy.SOURCE : 在编译阶段丢弃。这些注解在编译结束之后就不再有任何意义,所以它们不会写入字节码。@Override, @SuppressWarnings都属于这类注解。
● RetentionPolicy.CLASS : 在类加载的时候丢弃。在字节码文件的处理中有用。注解默认使用这种方式
● RetentionPolicy.RUNTIME : 始终不会丢弃,运行期也保留该注解,因此可以使用反射机制读取该注解的信息。我们自定义的注解通常使用这种方式。
一个简单的Annotations标记注解,表示是否将注解信息添加在java文档中。
子类可以继承父类的注解
- package com.lixi;
-
- import java.lang.annotation.*;
-
- @SuppressWarnings("all")
- @MyAnnotation
- public class Test02 {
- //测试元注解,重点掌握Target,Retention
- @MyAnnotation
- public void Demo() {
- }
- }
-
- //定义一个注解
- // Target 它表示我们自定义的注解可以用在那些地方
- @Target(value = {ElementType.METHOD, ElementType.TYPE})
- // Retention 它表示我们注解在什么时候还有效,RUNTIME > CLASS > SOURCE
- @Retention(value = RetentionPolicy.RUNTIME)
- // Documented 表示是否将我们的注解生成在JAVAdoc中
- @Documented
- // Inherited 子类可以继承父类的注解
- @Inherited
- @interface MyAnnotation {
-
- }
-
-
注意
1.Annotation型定义为@interface, 所有的Annotation会自动继承java.lang.Annotation这一接口,并且不能再去继承别的类或是接口.
2.参数成员只能用public或默认(default)这两个访问权修饰。
3.方法的名称就是参数的名称
4.返回类型就是参数类型(返回类型只能是基本类型String,enum,Class)
5.可以通过default来声明参数的默认值
6.如果只有一个参数成员,我们一般默认为value
- package com.lixi;
-
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
-
-
- @SuppressWarnings("all")
- public class Test03 {
- @Annotation2(schools = {"大学"},id=-1)
- public void Demo(){
- }
- @Annotation3("jili")
- public void Demo1(){
- }
- }
- @SuppressWarnings("all")
- @Target({ElementType.TYPE, ElementType.METHOD})
- @Retention(RetentionPolicy.RUNTIME)
- @interface Annotation2 {
- //注解的参数: 参数类型 + 参数名 + ()
- //default表示注解默认值,有了默认值,就不用给注解赋值
- String value() default "jili";
- int count () default 0;
- int id () ;
- String[] schools() ;
- }
- @SuppressWarnings("all")
- @Target({ElementType.TYPE, ElementType.METHOD})
- @Retention(RetentionPolicy.RUNTIME)
- @interface Annotation3 {
- //单个参数使用value,可以不用写value
- String value();
- }
一般的注解是没有那么多的参数的,上面只是演示