一种这样的情况是从 Bundle 中读取一个 int 并将其存储到受 @IndDef 注释限制的变量中:
public class MainActivity extends ActionBarActivity {
@IntDef({STATE_IDLE, STATE_PLAYING, STATE_RECORDING})
@Retention(RetentionPolicy.SOURCE)
public @interface State {}
public static final int STATE_IDLE = 0;
public static final int STATE_PLAYING = 1;
public static final int STATE_RECORDING = 2;
@MainActivity.State int fPlayerState = STATE_IDLE;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
fPlayerState = savedInstanceState.getInt(BUNDLE_STATE); //Causes "Must be one of: ..." error
必须有某种方式来抑制检查或从 int 转换为 @MainActivity.State int 以便在最后一行设置变量。
另一种情况是编写一个否定测试,调用带有注释参数的函数,故意传递错误的参数,以测试在这种情况下是否抛出异常。为了编译这样的测试,必须有一种方法来抑制注释检查。