Android-注解详解

本文详细介绍了Android注解的使用,包括IntDef和StringDef注解替代枚举、资源类型注解、Null注解以及其他实用注解,如Threading、Value Constraints等。通过注解,可以提高开发效率,及早发现程序错误,并增强代码描述性。文章总结了注解的重要作用,并给出了使用建议。
摘要由CSDN通过智能技术生成

Android-注解详解

背景

上一章,我们研究了 Java注解 的用法;紧跟着这章研究一下Android相关的注解的使用,比如我们熟悉的ButterKnife就是使用注解的方式实现对其使用,掌握注解的使用方法极大的方便了我们的开发效率


环境

使用Android注解前需要导入相关的包

 compile 'com.android.support:support-annotations:latest.integration'

注意:如果我们已经引入了appcompat则没有必要再次引用support-annotations,因为appcompat默认包含了对其引用

使用

Android注解给我们提供了三种主要和其他注释供我们使用:

  • IntDef和StringDef注解;

  • 资源类型注解;

  • Null注解;

  • 其他实用注解


IntDef和StringDef注解替代枚举

这里我们采用假设一个问题然后一步步解决学习:假设有一个User对象,我们需要记录user类型的变量,如何实现呢?

方案一

public class UserI {
   
    public static  int childe=0x1;
    public static  int man=0x2;
    public static  int girl=0x3;


    private int userType;

    public int getUserType() {
        return userType;
    }

    public void setUserType(int userType) {
        this.userType = userType;
    }
}

估计大家常用的就是这样的方式去解决这样的需求,但是上述实现存在一个问题:setUserType设置的是一个int类型的变量,既然如此我们可以如此调用:

    UserI userI=new UserI();
    /*正确调用*/
    userI.setUserType(userI.childe);

    /*错误调用*/
    userI.setUserType(100);

错误方式下的调用也不会抛出异常,所以这样的实现方式存在逻辑泄漏的危险!


方案二

既然如此:想必这个时候大家想到的解决办法就是枚举了,下面研究下枚举的实现

public class UserE {
   

    private UserEmun userType;

    public UserEmun getUserType() {
        return userType;
    }

    public void setUserType(UserEmun userType) {
        this.userType = userType;
    }

    public static enum UserEmun {
        childe,
        man,
        girl
    }
}

调用:

   UserE userE=new UserE();
   userE.setUserType(UserE.UserEmun.childe);

从实现方式和逻辑上看,方案二枚举确实能解决方案一存在的漏洞,但是这里有一点需要注意:Enum因为其相比方案一的常量来说,占用内存相对大很多而受到曾经被Google列为不建议使用。

既然枚举也有它相关的缺陷,那如何完美解决这样的需求呢,以下完美实现-就是Android中用注解来替换java的枚举;


完美方案

Android中新引入的替代枚举的注解有IntDefStringDef,他们唯一的区别一个是int类型,一个是string类型,下面我们就以IntDef为例讲解如何使用

构建定义注解

public class UserInter {
   
    public static final int childe = 0x1;
    public static final int man = 0x2;
    public static final int girl = 0x3;
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值