Skip to content Skip to sidebar Skip to footer

Enums And Android Annotation Intdef

I have an enum: public enum AppEnums { SERVICE_ERROR, CONNECTION_ERROR; } and I want to use it in an intDef of Android Annotation: @IntDef({AppEnums.CONNECTION_ERROR, AppE

Solution 1:

The main idea of IntDef annotation is to use set of int constants like an enum, but withoutenum. In this case you have to declare all constants manually.

@IntDef({Status.IDLE, Status.PROCESSING, Status.DONE, Status.CANCELLED})@Retention(RetentionPolicy.SOURCE)@interface Status {
    intIDLE=0;
    intPROCESSING=1;
    intDONE=2;
    intCANCELLED=3;
}

You can see detailed example here.

Solution 2:

Well, you can't quite do it that way. AppEnums.SERVICE_ERROR will never return int; it will return AppEnums.SERVICE_ERROR. That's the point of enumerated types.

What I can suggest is this:

publicstaticclassAppEnums {
    publicstaticfinalintCONNECTION_ERROR=0;
    publicstaticfinalintSERVICE_ERROR=1;
}

@IntDef({AppEnums.CONNECTION_ERROR,AppEnums.SERVICE_ERROR})public@interface ServiceErrors {
}

Copied from Yazazzello's comment below:

IntDef - new Enums for Android development. Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android. so IntDef where designed to replace Enums, you cannot use Enum in IntDef declarations

Solution 3:

@Retention(RetentionPolicy.SOURCE)@IntDef({NOT_STARTED, PENDING, COMPLETED})public@interface DownloadState {
    intNOT_STARTED=1;
    intPENDING=2;
    intCOMPLETED=3;
}

Solution 4:

the annotated element of integer type, represents a logical type and that its value should be one of the explicitly named constants.

NOTE: If the IntDef#flag() attribute is set to true, multiple constants can be combined.

@IntDef(flag = false,value = {AppEnums.CONNECTION_ERROR, AppEnums.SERVICE_ERROR})@Retention(RetentionPolicy.SOURCE)public@interface AppEnums {

  intCONNECTION_ERROR=0;
  intSERVICE_ERROR=1;
}

NOTE: If the IntDef#flag() attribute is set to true, multiple constants can be combined.

also you can Using @LongDef for long values and @StringDef for StringValues

Post a Comment for "Enums And Android Annotation Intdef"