您的位置:首页 > 编程语言 > Java开发

java学习之Java注解

2016-04-04 19:29 447 查看
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.利用反射机制解析注解
    public class ParseAnn {

public static void main(String[] args) {
// 使用类加载器加载类
try {

Class c = Class.forName("com.ann.test.child");
//2.找到类上面的注解
boolean isExit = c.isAnnotationPresent(Description.class);
if(isExit){
//3.拿到注解实例
Description d= (Description)c.getAnnotation(Description.class);
System.out.println(d.desc());
}
//4.找到方法上的注解 遍历所有的方法
Method []ms = c.getMethods();
for(Method m : ms ){
if(m.isAnnotationPresent(Description.class)){
Description d = (Description)m.getAnnotation(Description.class);
System.out.println(d.desc());
}
}
//另外一种解析方法
for(Method m:ms){
Annotation [] as = m.getAnnotations();
for(Annotation a :as){
if(a instanceof Description){
Description d = (Description)a;
System.out.println(d.desc());
}
}

}

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 开发框架