在Android中将参数化的枚举转换为枚举注释 [英] Convert parametized Enum to Enumerated Annotation in android

查看:138
本文介绍了在Android中将参数化的枚举转换为枚举注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对andriod @IntDef 注释有疑问.我知道在其基本用法上,应替换 enum .但是如果我有一个带有多个固定值的参数化枚举

I have a question regarding to the andriod @IntDef Annotation. I know that in its basic usage, it should replace the enum. But what if I have a parameterized enum with multiple hardwired values for example

public enum MyEnum {
  YES(true, 1),
  NO(false, 0);


  private boolean boolState;
  private boolean intState;

  MyEnum(boolean boolState, int intState) {
    this.boolState = boolState;
    this.intState = intState;
  }

  public boolean getBoolState() {
    return boolState;
  }

  public int getIntState() {
    return intState;
  }
}

如何在Android中将其替换为枚举注释?

在这种情况下,做这样的事情甚至暗示吗?我搜索过到处都是,但我还没有找到任何答案.

Is it even suggestive to do something like that in this case? I searched everywhere, but I haven't found any answer for that.

提前谢谢!

推荐答案

我认为您无法找到任何东西,因为:

I don't think you would be able to find anything because:

IntDef是一种替换有参数的整数枚举的方法应该只接受显式的int值.

IntDef is a way of replacing an integer enum where there's a parameter that should only accept explicit int values.

您可以在此处了解更多信息.枚举注释适用于简单类型,您也可以将其用于字符串 StringDef .需要枚举功能时使用枚举.不要严格避免它.对于您的情况,我认为创建类而不是枚举看起来像这样:

you can read more about it here. Enumerated annotations are for simple types, you could use it for strings also StringDef. Use enum when you need its features. Don't avoid it strictly. For your case I think creating class instead of enum would look like this:

public class MyEnum {

    public static final MyEnum YES = new MyEnum(true, 1);
    public static final MyEnum NO = new MyEnum(false, 0);

    private boolean boolState;
    private int intState;

    MyEnum(boolean boolState, int intState) {
        this.boolState = boolState;
        this.intState = intState;
    }

    public boolean getBoolState() {
        return boolState;
    }

    public int getIntState() {
        return intState;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        MyEnum myEnum = (MyEnum) o;

        return boolState == myEnum.boolState && intState == myEnum.intState;
    }

}

,您可以在代码中使用常量.但是,如果使用枚举,您将拥有类型检查(您将只能接受列出的值)和方法重载(每个枚举常量可以具有自己的方法实现).如果您想使用更少的空间,这就是为什么要避免使用枚举的唯一原因,那么我建议您这样做是不值得的.

and you could use constants in your code. But if using enums you will have type checking (you'll be able to accept only listed values) and method overloading (every enum constant can have its own implementation of a method). If you want to use less space and that is the only reason why you want to avoid using enum I would suggest you that it's not worth it.

这篇关于在Android中将参数化的枚举转换为枚举注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆