Take the following example.
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
The data is pulled from the database with a Cursor and put into my custom class.
request.setStatus(cursor.getInt(COLUMN_STATUS));
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;
}
@IntDef({STATUS_UNKNOWN, STATUS_DOWNLOADING, STATUS_COMPLETE, STATUS_PAUSED, STATUS_CANCELLED, STATUS_TEMP_PAUSED, STATUS_QUEUED})
@Retention(RetentionPolicy.SOURCE)
public @interface StatusEnum {}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With