注解(二)-Android注解

环境

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

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

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

  • IntDef和StringDef注解;
  • 资源类型注解;
  • Null注解;
  • 其他实用注解

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

使用IntDef和StringDef注解替代枚举

public class UserInter {
    public static final int childe = 0x1;
    public static final int man = 0x2;
    public static final int girl = 0x3;
    public static final int other = 0x4;

    @IntDef({childe, man, girl})
    @Retention(RetentionPolicy.SOURCE)
    public @interface UserInters{}

    private int userType;

    @UserInters
    public int getUserType() {
        return userType;
    }

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

使用我们自定义的注解类UserInters,在get方法上定义返回类型,和set方法中设置传入参数的类型,这样在调用get和set方法时,编译器会自动帮我们检测是否合法!

资源类型注解

前缀+Res;
在这里插入图片描述

Null注解

null注解对应的有两个详细的注解:

  • @NonNull:不能为空

  • @Nullable:可以为空

其他注解

Threading 注解

  • @UiThread: UI线程
  • @MainThread :主线程
  • @WorkerThread: 子线程
  • @BinderThread : 绑定线程

Value Constraints注解

  • @Size 定义长度大小,可选择最小和最大长度使用
  • @IntRange IntRange是用来指定int类型范围的注解
  • @FloatRange FloatRange和IntRange用法一样
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        testDo("");

        testDo("111");

        testDo("1");
    }

    private void testDo(@Size(min = 1,max = 2)String s){
        Log.e("tag","-------->"+s);
    }
}

@CallSuper注解

@CallSuper注解主要是用来强调在覆盖父类方法时,需要实现父类的方法,及时调用对应的super.***方法,当用@CallSuper修饰了该方法,如果子类覆盖的后没有实现对呀的super方法会抛出异常

在这里插入图片描述

总结:
注解的作用:
提高我们的开发效率
更早的发现程序的问题或者错误
更好的增加代码的描述能力
更加利于我们的一些规范约束
提供解决问题的更优解

参考原文:
android注解详解

猜你喜欢

转载自blog.csdn.net/fendouwangzi/article/details/83536375