`
xmong
  • 浏览: 259050 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

java annotation注解

阅读更多
1. Annotation的声明方式
Annotation类型那个声明于一般的接口声明极为相似,只是其关键字为@interface,其属性必须带有小括号,其实更像定义方法,下面文章以属性称之。

2. 常见的几种annotation
•  @Override: 用在方法,说明这个方法打算重写父类中的另一个方法的声明。
•  @Deprecated: 用于所有元素,说明该方法或属性等已经过时,不建议使用,编译器会产生警告信息,通常是因为它很危险或存在更好的选择。
•  @SuppressWarnings: 取消显示指定的编译器警告。

3.自定义annotation
3.1 @Retention
表示注释类型的注释要保留多久,注解的生命周期,不声明默认为class策略,可选下面三种策略:
1,RetentionPolicy.SOURCE: 这个Annotation类型的信息只会保存在程序源码中,源码如果经过了编译之后,Annotation的数据就会消失,并不会保存在编译好的.class二进制文件中。
2,RetentionPolicy.CLASS: 这个Annotation类型的信息保留在程序源码中,同时也会保存在编译好的.class文件中,在执行的时候并不会加载到JVM中。(默认)
3,RetentionPolicy.RUNTIME: 表示在源码、编译好的.class文件中保存信息,在执行的时候会把这些信息加载到JVM中,这样可以使用反射将其信息获取出来。

3.2 @Target
表示注解类型所使用的程序元素,不声明可以用在任一元素中。
1,ElementType.ANNOTATION_TYPE: 注释类型
2,ElementType.CONSTRUCTOR: 构造方法
3,ElementType.FIELD: 字段(包括枚举常量)
4,ElementType.LOCAL_VARIABLE: 局部变量
5,ElementType.METHOD: 方法
6,ElementType.PACKAGE: 包
7,ElementType.PARAMETER: 参数
8,ElementType.TYPE: 类Class、接口Interface(包括注释类型Annotation)或枚举Enum

3.3 @Documented
表示某一类型的注释将通过javadoc和类似的默认工具进行文档化,文档化时其注释部分将成为注释元素的公共API的一部分。

3.3 @Inheried
表示允许子类继承父类中的注解

4. 案例实现
TestAnnotation.java   自定义Annotation类
Test.java  测试类

package com.anotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 *  自定义注解类
 * @author zhimeng
 */

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {

    /**
     * 为注解添加属性name,默认值为:zhimeng
     */
    public String name() default "zhimeng";
    
    public String mail();
    
}



测试注解

package com.anotation;

import java.lang.reflect.Method;

/**
 * @author zhimeng
 */
public class Test {

    @TestAnnotation(mail = "")
    public void test1(){}
    
    /**
     * 调用注解赋值
     */
    @TestAnnotation(name="xiaohong", mail = "zhimeng@126.com")
    public void test2(){}
    
    
    public static void main(String[] args) {
        Method[] methods = Test.class.getDeclaredMethods();
        
        for (Method method : methods) {
            /**
             * 检查方法是否有注解
             */
            boolean hasAnnotation = method.isAnnotationPresent(TestAnnotation.class);
            if(hasAnnotation){
                //获取注解
                TestAnnotation testAnnotation = method.getAnnotation(TestAnnotation.class);
                System.out.println("method:"+method.getName()
                                   +", name:"+testAnnotation.name()
                                   +", mail:"+testAnnotation.mail());
            }
        }
    }
    
    
}


输出结果:
method:test1, name:zhimeng, mail:
method:test2, name:xiaohong, mail:zhimeng@126.com

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics