JAVA注解示例

来源:互联网 发布:知已的意思 编辑:程序博客网 时间:2024/06/06 14:10

Annotation(注解)是JDK5.0及以后版本引入的。它可以用于创建文档,跟踪代码中的依赖性,甚至执行基本编译时检查。注解是以‘@注解名’在代码中存在的,根据注解参数的个数,我们可以将注解分为:标记注解、单值注解、完整注解三类。它们都不会直接影响到程序的语义,只是作为注解(标识)存在,我们可以通过反射机制编程实现对这些元数据的访问。另外,你可以在编译时选择代码里的注解是否只存在于源代码级,或者它也能在class文件中出现。

注解的语法比较简单,除了@符号的使用以外,它基本上与java的固有语法一致,java内置了三种注解,定义在java.lang包中。
      @Override  表示当前方法是覆盖父类的方法。
      @Deprecated  表示当前元素是不赞成使用的。
      @SuppressWarnings 表示关闭一些不当的编译器警告信息。

下面是一个定义注解的实例

package com.annotation.test;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/**   * 元注解@Target,@Retention,@Documented,@Inherited   *    *     @Target 表示该注解用于什么地方,可能的 ElemenetType 参数包括:   *         ElemenetType.CONSTRUCTOR 构造器声明   *         ElemenetType.FIELD 域声明(包括 enum 实例)   *         ElemenetType.LOCAL_VARIABLE 局部变量声明   *         ElemenetType.METHOD 方法声明   *         ElemenetType.PACKAGE 包声明   *         ElemenetType.PARAMETER 参数声明   *         ElemenetType.TYPE 类,接口(包括注解类型)或enum声明   *            *     @Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括:   *         RetentionPolicy.SOURCE 注解将被编译器丢弃   *         RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃   *         RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。   *            *     @Documented 将此注解包含在 javadoc 中   *        *     @Inherited 允许子类继承父类中的注解   *      */@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited/** * 定义注解 Test   * 注解中含有两个元素 id 和 description   * description 元素 有默认值 "no description"   */public @interface TestAnnotation {public int id();public String content() default "no content";}


下面是一个使用注解 和 解析注解的实例

package com.annotation.test;import java.lang.reflect.Method;public class Test01 {/** * 被注解的三个方法 */@TestAnnotation(id = 1, content = "this is method1")public void method1() {}@TestAnnotation(id = 2)public void method2() {}@TestAnnotation(id = 3, content = "this is method3")public void method3() {}/** * 解析注解,将Test01类 所有被注解方法 的信息打印出来 */public static void main(String[] args) {Method[] methods = Test01.class.getMethods();for (Method m : methods) {/** * 判断方法中是否有指定注解类型的注解 */boolean hasAnnotation = m.isAnnotationPresent(TestAnnotation.class);if (hasAnnotation) {TestAnnotation annotation = m.getAnnotation(TestAnnotation.class);System.out.println(m.getName() + " Annotation(id=" + annotation.id() + ", content=" + annotation.content() + ")");}}}}

 

输出结果如下:
method1 Annotation(id=1, content=this is method1)method2 Annotation(id=2, content=no content)method3 Annotation(id=3, content=this is method3)