Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test whether an int is included in IntDef definition

Tags:

android

Take the following example.

Error message

Must be one of: DownloadRequest.STATUS_UNKNOWN, DownloadRequest.STATUS_DOWNLOADING, DownloadRequest.STATUS_COMPLETE, DownloadRequest.STATUS_PAUSED, DownloadRequest.STATUS_CANCELLED, DownloadRequest.STATUS_TEMP_PAUSED, DownloadRequest.STATUS_QUEUED

Query database

The data is pulled from the database with a Cursor and put into my custom class.

request.setStatus(cursor.getInt(COLUMN_STATUS));

Set custom builder

This custom class method takes an integer and sets its internal status. The integer is validated by an IntDef annotation.

@NonNull
public Builder setStatus(@StatusEnum int status) {
    mInstance.mStatus = status;
    return this;
}

The IntDef annotation

@IntDef({STATUS_UNKNOWN, STATUS_DOWNLOADING, STATUS_COMPLETE, STATUS_PAUSED, STATUS_CANCELLED, STATUS_TEMP_PAUSED, STATUS_QUEUED})
@Retention(RetentionPolicy.SOURCE)
public @interface StatusEnum {}

The issue

The only values that enter the database are values given by the StatusEnum annotation. This is validated at all steps. I would still validate the information coming from the database.

How can I test whether an integer exists in an IntDef definition. I could test that given integer is one of the constants. However, that will increase future code maintenence.

like image 612
Knossos Avatar asked Oct 21 '25 03:10

Knossos


1 Answers

Unfortunately you can't look at the values of @IntDef because as you can see in the source code [1] of the annotation:

@Retention(SOURCE)
@Target({ANNOTATION_TYPE})
public @interface IntDef {
    /** Defines the allowed constants for this element */
    long[] value() default {};

    /** Defines whether the constants can be used as a flag, or just as an enum (the default) */
    boolean flag() default false;
}

it is marked with SOURCE as RetentionPolicy:

SOURCE
Annotations are to be discarded by the compiler.

For this reason you can't iterate at runtime.

like image 115
Mattia Maestrini Avatar answered Oct 24 '25 18:10

Mattia Maestrini