Java Annotation浅析

  

什么是Annotation

(1)注解不是程序本身(也就是说Annotation不能影响程序代码的执行,无论增加、删除 Annotation,代码都始终如一的行),可以对程序作出解释(和注释没区别)
(2)可以被其他程序(比如:编译器等)读取

注解的作用

(1)生成文档。如生成javadoc的@see @param @return
(2)跟踪代码依赖性,实现替代配置文件的功能。如spring中@Service等注解。
(3)在编译时期进行格式检查。如@Override放在方法前,如果你的方法不是覆盖超类的方法,编译时期就会报错。

如何使用注解

“@注释名”在代码中存在,还可以添加一些参数.
例如:@SuppreWarning(value="unchecked")

注解可以附加在package,class,method,field等上面,相当于给它们添加了额外的辅助信息,我们可以通过反射机制编程实现对这些元数据的访问。
class Demo{
    @Override
    public Stirng toStirng(){
        return "";
    }
}

java内置注解

@Override
只使用于修饰方法,表示一个方法声明打算重写超类中的另一个方法声明

@Deprecated
修饰方法,属性,类,表示不鼓励程序员使用这样的元素

@SuppressWarnings抑制编译期发出某些警告


| ----------- | --------------------------------------------------- |
| deprecation | 过时的类或方法警告                                     |
| ----------- | --------------------------------------------------- |
| unchecked   | 未检查的转换时警告                                     |
| ----------- | --------------------------------------------------- |
| fallthrough | switch语句穿透警告                                    |
| ----------- | --------------------------------------------------- |
| pat         | 类路径、源文件路径等有不存在的路径时的警告                 |
| ----------- | --------------------------------------------------- |
| serial      | 在可序列化的类上缺少serialVersionUID定义时警告           |      
| ----------- | --------------------------------------------------- |
| all         | 关于上面的所有情况的警告                                |
| ----------- | --------------------------------------------------- |

自定义注解

元注解:
@Target,@Retention,@Documented,@Inherited 


| --------------------------- | ---------------------------------- |
| ElemenetType.FIELD          | 域声明(包括 enum 实例)              |
| --------------------------- | ---------------------------------- |
| ElemenetType.LOCAL_VARIABLE | 局部变量声明                         |
| --------------------------- | ---------------------------------- |
| ElemenetType.CONSTRUCTOR    | 构造器                              |
| --------------------------- | ---------------------------------- |
| ElemenetType.METHOD         | 方法声明                            |
| --------------------------- | ---------------------------------- |
| ElemenetType.PACKAGE        | 包声明                              |
| --------------------------- | ---------------------------------- |
| ElemenetType.PARAMETER      | 参数声明                            |
| --------------------------- | ---------------------------------- |
| ElemenetType.TYPE           | 类,接口(包括注解类型)或enum声明      |


| ------- | ---------------------------------------- |
| SOURCE  | 源文件中保留,class文件不保留                |
| ------- | ---------------------------------------- |
| CLASS   | class文件保留,不加载到内存,运行时不保留      |
| ------- | ---------------------------------------- |
| RUNTIME | 运行时可以通过反射获得注解内容                |

自定义注解默认值问题: 

注解必须要有值。我们定义注解元素时,经常使用空字符串、0作为默认值。 也经常使用负数(比如:-1)表示不存在的含义。

案例:自定义注解并且使用反射处理读取注解内容

/**
 * 学生名注解
 */

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface StudentName {
    String value() default "";
}

/**
 * 学生性别注解
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface StudentSex {
    /**
     * 性别枚举
     */
    public enum Sex {GRIL, BOY};

    /**
     * 性别属性
     * @return
     */

    Sex studentSex() default Sex.BOY;
}

/**
 * 学校注解
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface School {
    /**
     * 学校名称
     */
    public String name() default "";

    /**
     * 学校排名
     * @return
     */
    public int id() default -1;
}

/**
 * 使用注解
 */
public class Student {
    @StudentName("ximing")
    private String name;
    @StudentSex(studentSex = StudentSex.Sex.GRIL)
    private String sex;
    @School(name = "北大", id = 1)
    private String school;
}

/**
 * 读取注解信息
 */
public class HandleAnnotation {
    public static void getStudentInfo(Class<?> clazz){
        String strStudentName = "学生名称: ";
        String strStudentSex = "学生性别: ";
        String strStudentSchool = "学生所在学校: ";

        Field[]  fields  = clazz.getDeclaredFields();

        for(Field field : fields){
            if(field.isAnnotationPresent(StudentName.class)){
                StudentName studentName =  field.getAnnotation(StudentName.class);
                strStudentName = strStudentName + studentName.value();
                System.out.println(strStudentName);
            }else if(field.isAnnotationPresent(StudentSex.class)){
                StudentSex studentSex =  field.getAnnotation(StudentSex.class);
                strStudentSex = strStudentSex + studentSex.studentSex().toString();
                System.out.println(strStudentSex);
            }else if(field.isAnnotationPresent(School.class)){
                School school = field.getAnnotation(School.class);
                strStudentSchool = strStudentSchool + "学校名称: " + school.name().toString() +
                        "排名: " + school.id();
                System.out.println(strStudentSchool);
            }
        }

    }

    public static void main(String[] args) {
        HandleAnnotation.getStudentInfo(Student.class);
    }
}

//执行结果
学生名称: ximing
学生性别: GRIL
学生所在学校: 学校名称: 北大排名: 1

推荐博客:http://www.cnblogs.com/peida/archive/2013/04/26/3038503.html


转载于:https://my.oschina.net/u/2361475/blog/597726

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值