Android - 在 @interface 内部放置 @IntDef 值是否可以?

9 浏览
0 Comments

Android - 在 @interface 内部放置 @IntDef 值是否可以?

我正在尝试在Android开发中实现@IntDef注解。

第一种方法:将定义分离在一个Constant.java类中,看起来很好:

public class Constant {
   @IntDef(value={SORT_PRICE, SORT_TIME, SORT_DURATION})
   @Retention(RetentionPolicy.SOURCE)
   public @interface SortType{}
   public static final int SORT_PRICE = 0;
   public static final int SORT_TIME = 1;
   public static final int SORT_DURATION = 2;
}

用法:

@Constant.SortType int sortType = Constant.SORT_PRICE;

但是当一个文件中有多个定义(例如UserType,StoreType等)时,情况变得非常混乱。

第二种方法:所以我想到了这样的方法来区分定义之间的值:

public class Constant {
   @IntDef(value={SortType.SORT_PRICE, SortType.SORT_TIME, SortType.SORT_DURATION})
   @Retention(RetentionPolicy.SOURCE)
   public @interface SortTypeDef{}
   public static class SortType{
       public static final int PRICE = 0;
       public static final int TIME = 1;
       public static final int DURATION = 2;
   }
}

用法:

@Constant.SortTypeDef int sortType = Constant.SortType.PRICE;

但是如你所见,我为它创建了两个不同的名称:SortTypeDefSortType

第三种方法:我尝试将可能的值列表移到@interface中:

public class Constant {
   @IntDef(value={SortType.SORT_PRICE, SortType.SORT_TIME, SortType.SORT_DURATION})
   @Retention(RetentionPolicy.SOURCE)
   public @interface SortType{
       int PRICE = 0;
       int TIME = 1;
       int DURATION = 2;
   }
}

用法:

@Constant.SortType int sortType = Constant.SortType.PRICE;

虽然它确实可以工作,但是我不知道其中的缺点。

@IntDef的可能值放在@interface中可以吗?这三种方法之间是否有性能差异?

0