首页 > 编程 > Java > 正文

java注解解析

2019-11-08 18:33:45
字体:
来源:转载
供稿:网友

java元注解

元注解作用是负责注解其他注解,java5.0定义了四个标准的元注解。包括:@Target、@Documented、@Retention、@Inherit。

@Target注解:它用于描述注解可以修饰的类型。可以修饰的类型为:TYPE(类、接口、枚举)、FIELD、METHOD(方法声明)、PARAMETER(参数)、CONSTRUCTOR(构造方法)、LOCAL_VARIABLE(本地变量)、ANNOTATION_TYPE(注解类型声明)、PACKAGE(包)。

其代码如下所示: 这里写图片描述

@Retention注解:用于表示该注解的作用阶段。其参数可以取RetentionPolicy中的值。如: SOURCE:作用于源代码中,编译阶段被去除。 CLASS:可以被编译进Class文件中,但是虚拟机对其忽略。 RUNTIME:可以被编译进Class文件,虚拟机在运行期使用。

其代码为: 这里写图片描述

@Documented注解:用于在生成API文档的时候,使得该注解可以呈现在使用该注解的API上。 这里写图片描述

@Inherit注解:是一个标记注解,用于描述一个注解可以被继承。如果一个类使用了(@Interit标注的注解)的话,那么该注解可以被该类的子类继承。 如果使用反射去查找一个标注了@Inherit注解的类的时候,反射代码会检查该类及其父类,直到找到标注了该注解的顶层类。

其代码如下: 这里写图片描述

自定义注解

根据上面的元注解我们可以定义自己的注解,注解在定义的时候,可以指定其不同的参数,以及该参数的默认值。

@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface PersonAnno { String name() default ""; int age() default 0;}

这里自己定义了一个注解,其中添加了两个参数,分别是name和age并设置了默认值。

根据上面定义的注解,其保留到运行时,且标注于方法上。

public class Person { @PersonAnno(name = "wy", age = 20) public void getPerson() { }}

下面针对该注解进行测试。

public class MainTest { public static void main(String[] args) throws Exception { Person person = new Person(); Class pers = person.getClass(); // 反射拿到方法 Method method= pers.getDeclaredMethod("getPerson"); // 获取注解 PersonAnno ana = method.getAnnotation(PersonAnno.class); System.out.PRintln(ana.name() + ":" + ana.age()); }}

输出结果如下:

wy:20

注解本质

本质上注解会被编译为继承了(Annotation接口)的接口。 反编译上面的PersonAnno.class可以看到代码如下: 这里写图片描述 从上面的反编译后的代码可以看出注解实际上被编译为接口了。

/** * The common interface extended by all annotation types. Note that an * interface that manually extends this one does <i>not</i> define * an annotation type. Also note that this interface does not itself * define an annotation type. * * More information about annotation types can be found in section 9.6 of * <cite>The Java&trade; Language Specification</cite>. * * @author Josh Bloch * @since 1.5 */public interface Annotation {}

这里Annotation接口中已经给出了说明,该接口被所有的注解类型的接口继承。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表