注解

2017-01-12  本文已影响13人  最最最最醉人

什么是注解

注解(Annotation)是Java5的一个新特性,是插入在代码中的一种注释或者说是一种元数据(meta data),这些注释信息可以在编译期使用预编译工具进行获取处理,也可以在运行期使用Java反射机制来获取,这取决于你的注解类型。

标准注解

在Java的JDK中内置了一些系统自带的注解,这些注解也常称为标准注解,常见的有:@Override, @Deprecated, @SuppressWarnings


@Override

@Override作用于方法,表示被标注的方法重载了父类的方法。
其实重载父类的方法也可以不写@Override注解,但是写上了,若该重载的方法写错了方法名那么在编译期就会有出现警告
当我们写Activity的时候,通过都会写onCreate这个方法

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Deprecated

当一个类型或者类型成员使用@Deprecated标记则表示建议不再使用该元素。

public class User {
    public int id;

    public int getId() {
        return id;
    }
    @Deprecated
    public void setId(int id) {
        this.id = id;
    }
}

@Deprecated使用

@SuppressWarnings

@SuppressWarnings就是抑制警告,它被用于关闭编译器对类、方法、成员变量、变量初始化的警告。
当我们定义了一个变量,但是没有使用它的时候,会有这么一个警告。

警告

但是我们加上@SuppressWarnings注解之后,警告就消失了

@SuppressWarnings

可以看到,这个注解和之前两个有点不一样,该注解多了一个参数。通过它的名字我们可以知道,unused表示未使用的。@SuppressWarnings还有许多其他参数

自定义注解

除了使用系统提供的注解,我们当然也可以自定义注解。
使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节。在定义注解时,不能继承其他的注解或接口。@interface用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数。方法的名称就是参数的名称,返回值类型就是参数的类型(返回值类型只能是基本类型、Class、String、enum)。可以通过default来声明参数的默认值。

定义注解格式:

public @interface 注解名 {定义体}

注解参数的可支持数据类型:

  1. 所有基本数据类型(int,float,boolean,byte,double,char,long,short)
  2. String类型
  3. Class类型
  4. enum类型
  5. Annotation类型
  6. 以上所有类型的数组

**Annotation类型里面的参数该怎么设定: **

  1. 只能用public或默认(default)这两个访问权修饰.例如,String value();这里把方法设为defaul默认类型;
  2. 只能用可支持的数据类型
  3. 如果只有一个参数成员,最好把参数名称设为"value"。这样在使用注解的时候,就不用在指定key了
// 这是拥有两个属性的自定义注解
public @interface MyAnnotation {    
    public String value() default "";    
    public int id();
}
// 这是只有一个属性的自定义注解,所以这里推荐把属性名设置为value,使用的时候更加方便
public @interface ValueAnnotation {
    public String value() default "";    
}

自定义注解的使用

@MyAnnotation(id=12)
@ValueAnnotation()
public class Test {}

获取自定义注解属性

自定义注解中往往都带有属性,那么怎么获取这些注解的属性值呢?
通常都是有一个套路的

private void getAnnotationValue() {
    MyAnnotation annotation = null;
    Class clazz = Test.class;
    // 判断是否有MyAnnotation注解存在
    boolean isPresent = clazz.isAnnotationPresent(MyAnnotation.class);
    if (isPresent) {
        // 获取注解
        annotation = (MyAnnotation) clazz.getAnnotation(MyAnnotation.class);
        // 得到注解的属性值
        String value = annotation.value();
        int id = annotation.id();
        System.out.println("----> annotation=" + annotation);
        System.out.println("----> value=" + value + ",id=" + id);
    }
}

元注解

元注解的作用就是负责注解其他注解。Java5.0定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明。Java5.0定义的元注解:@Target、@Retention、@Documented、@Inherited


@Target:

@Target说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标。
@Target有如下一些值:

public enum ElementType {
    /**
     * Class, interface or enum declaration.
     * 用于描述类、接口(包括注解类型) 或enum声明
     */
    TYPE,
    /**
     * Field declaration.
     * 用于描述域
     */
    FIELD,
    /**
     * Method declaration.
     * 用于描述方法
     */
    METHOD,
    /**
     * Parameter declaration.
     * 参数声明
     */
    PARAMETER,
    /**
     * Constructor declaration.
     * 用于描述构造器
     */
    CONSTRUCTOR,
    /**
     * Local variable declaration.
     * 用于描述局部变量
     */
    LOCAL_VARIABLE,
    /**
     * Annotation type declaration.
     * 用于描述注解
     */
    ANNOTATION_TYPE,
    /**
     * Package declaration.
     * 用于描述包
     */
    PACKAGE
}

使用实例: 我们来看看@Override 的源码

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {}

可以看出来,@Override就是作用于方法的。


@Retention:

@Retention定义了Annotation的有效范围,类似于Android中常提到的生命周期。Java文件从生产到执行,要经过三个主要的阶段:java源文件,Class文件,JVM运行。
与此类似,有的Annotation仅出现在源代码中而被编译器丢弃,而另一些却被编译在Class文件中;有的编译在Class文件中的Annotation在运行时会被虚拟机忽略,而另一些在运行时被读取读取。
所以,在@Retention中使用RetentionPoicy标明注解会存留到哪个阶段,RetentionPoicy有三个值:

使用实例: 我们来看看@Deprecated的源码

@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Deprecated {}

可以看出来,在这段源码中用@Retention(RetentionPolicy.RUNTIME)标明该注解会保留至运行时。


@Documented:

@Documented表示在生成javadoc文档时将该Annotation也写入到帮助文档。 Documented是一个标记注解,没有成员。


@Inherited:

@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。

简单的运行时注解示例

先定义三个Runtime注解,包括类、方法、字段,

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface run_classInfo {
    String value();
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface run_methodInfo {
    String name() default "long";
    String data();
    int id() default 365;
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface run_fieldInfo {
    int[] value();
}

然后使用它们

@run_classInfo("类注解RunTime Class")
public class RunTimeTest {
    @run_fieldInfo(value = {77, 88})
    public String fieldInfo = "filedInfo";

    @run_fieldInfo(value = {163})
    public int id = 55;

    @run_methodInfo(name = "whyalwaysmea", data = "haha")
    public static String getMethod() {
        return RunTimeTest.class.getSimpleName();
    }
}

解析注解

/**
 * 解析运行时注解
 */
private void showRunTimeInfo() {
    StringBuffer sb = new StringBuffer();
    //获取Class 注解
    Class<?> clazz = RunTimeTest.class;
    Constructor<?>[] constructors = clazz.getConstructors();
    //获取包含的注解类信息
    run_classInfo runClassInfo = clazz.getAnnotation(run_classInfo.class);
    if (runClassInfo != null) {
        //获取class注解
        sb.append("Class注解: ").append("\n");
        sb.append(Modifier.toString(clazz.getModifiers())).append(" ")
                .append(clazz.getSimpleName()).append("\n");

        sb.append("注解值:").append("\n")
                .append(runClassInfo.value()).append("\n\n");
    }

    //获取Field注解
    sb.append("Field注解:").append("\n");
    Field[] fields = clazz.getDeclaredFields(); //获取自身的不包括继承类
    for (Field field : fields) {
        //获取field注解类信息
        run_fieldInfo fieldInfo = field.getAnnotation(run_fieldInfo.class);
        if (fieldInfo != null) {
            sb.append(Modifier.toString(field.getModifiers())).append(" ")
                    .append(field.getType().getSimpleName()).append(" ")
                    .append(field.getName()).append("\n");
            sb.append("注解值: ").append("\n")
                    .append(Arrays.toString(fieldInfo.value())).append("\n\n");
        }
    }

    //获取Method 注解
    sb.append("Method注解: ").append("\n");
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
        run_methodInfo methodInfo = method.getAnnotation(run_methodInfo.class);
        if (methodInfo != null) {
            sb.append(Modifier.toString(method.getModifiers())).append(" ")
                    .append(method.getReturnType().getSimpleName()).append(" ")
                    .append(method.getName()).append("\n");
            sb.append("注解值:").append("\n");
            sb.append("name: ").append(methodInfo.name()).append("\n");
            sb.append("data: ").append(methodInfo.data()).append("\n");
            sb.append("id: ").append(methodInfo.id()).append("\n");
        }

    }
    tvDes.setText(sb.toString());
}

相关链接

注解基础

详解Android主流框架不可或缺的基石

上一篇下一篇

猜你喜欢

热点阅读