Java笔记(二十) 注解

注解

一、内置注解

Java内置了一些常用注解:

1.@Override

该注解修饰一个方法,表示当前类重写了父类的该方法。

2.@Deprecated 

该注解可以修饰类、方法、字段、参数等。表示对应的代码已经过时,不应该被使用。

它是一种警告,不是强制性的。当一个元素被注解为Deprecated时,应该在Java文档中说明替代方案。

3.@SuppressWarnings 

该注解表示,压制Java编译器警告,它有一个必填参数表示压制那种类型的警告。

可以修饰大部分代码元素。

二、创建注解

注解的定义,如@SuppressWarnings的定义

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
    String[] value();
}

元注解:用于定义注解本身

1)@Target:表示注解的目标,其中的ElementType是个枚举,主要可选值有:

TYPE:表示类、接口(包括注解),或者枚举声明;

FIELD:字段、包括枚举常量;

METHOD:方法;

PARAMETER:表示方法参数;

CONSTRUCTOR:构造方法;

LOCAL_VARIABLE:本地变量。

如果没有声明@Target,默认适用于所有类型。

2)@Retention:表示注解信息保留到什么时候,取值只能有一个,类型为RetentionPolicy,

它是一个枚举,取值有:

SOURCE:只保留在源代码中,编译器将代码编译为字节码后文件就会丢掉。

CLASS:保留到字节码文件中,但Java虚拟机将文件加载到内存时不一定会在内存中保留。

RUNTIME:一直保留到运行时。

3)@Document:表示注解信息包含到生成的文档中。

4)@Inherited:例子:

    public class InheritDemo {
        @Inherited
        @Retention(RetentionPolicy.RUNTIME)
        static @interface Test {
        }
        @Test
        static class Base {
        }
        static class Child extends Base {
        }
        public static void main(String[] args) {
            System.out.println(Child.class.isAnnotationPresent(Test.class)); //true
        }
    }

注意:与接口和类不同,注解不能被继承。

三、查看注解信息

利用反射机制,我们可以查看和利用注解信息。

Class、Field、Method、Constructor都有如下方法:

//获取所有注解
public Annotation[] getAnnotations()
//获取本元素上直接声明的注解,忽略@Inherited来的
public Annotation[] getDeclaredAnnotations()
//获取指定类型的注解,没有返回null
public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
//判断是否有指定类型的注解
public boolean isAnnotationPresent(
Class<? extends Annotation> annotationClass)

其中Annotation是一个注解,表示接口:

public interface Annotation {
    boolean equals(Object obj);
    int hashCode();
    String toString();
    //返回真正的注解类型
    Class<? extends Annotation> annotationType();
}

实际上内部实现时,所有的注解类型都是扩展的Annotation。

对于Method和Contructor,它们都有方法参数,而参数也可以有注解,所有它们都有如下方法:

public Annotation[][] getParameterAnnotations()

返回一个二维数组,每个参数对应一个一维数组。

原文地址:https://www.cnblogs.com/Shadowplay/p/9988550.html