java学习之Java注解

来源:互联网 发布:笑郭网络验证教程 编辑:程序博客网 时间:2024/05/21 21:49

1.什么是Java 注解(annotation)

     维基百科给出的定义:

    In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Unlike Javadoc tags, Java annotations can be reflective in that they can be embedded in class files generated by the compiler and may be retained by the Java VM to be made retrievable at run-time.It is possible to create meta-annotations out of the existing ones in Java.

   注解(Annotation),也叫元数据。一种代码级别的说明。它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明,注释。

     2. annotatio分类

    按照运行机制(生命周期)分:

        a.  源码注解:注解只在源文件中存在

  b. 编译时注解:注解在.class和.java文件中都有效

  c. 运行时注解:在运行时依然有效,可以影响程序的逻辑。

按照来源分:

 a. jdk中定义的注解 @Override @Deprecated @SuppressWarnings("")

 b. 来自第三方的注解,如Spring中的注解@Autowired

 c. 自定义注解

3. 自定义注解方式

1)语法

  @Target(ElementType.ANNOTATION_TYPE)

  @Retention(RetentionPolicy.RUNTIME)

  @Inherited

  @Documented

例:

  @Target({ElementType.METHOD,ElementType.TYPE})
       @Retention(RetentionPolicy.RUNTIME)
       @Inherited
       @Documented
        public @interface Description {
               String desc();//无参数

  }

 注:(1)成员类型必须是 基本类型,String,Class,Annotation,Enumration

        (2)如果注解类只有一个成员,可以取名为values,在使用时可以忽略成员名和赋值。

        (3)可以没有成员

        (4)可以设置默认值, int age() default 18;

4.使用自定义注解方法

  @<注解名>(<成员名>=<要赋的成员值>,...)

  @Description(desc="i am a interface")
        public class Person {
        @Description(desc="i am a method")
        public String name(){

              return null;
                       }

              }

5.利用反射机制解析注解

    

1 0