在特殊情况下如何禁用 Android @IntDef 注释检查? [英] How do I disable Android @IntDef annotation checks in special cases?
问题描述
这样的一种情况是从 Bundle 中读取一个 int 并将其存储到受@IndDef 注释限制的变量中:
One such case is reading an int from a Bundle and storing it into the variable restricted by @IndDef annotation:
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 以便在最后一行中设置变量.
There must be some way of suppressing the check or casting from int to @MainActivity.State int in order to set the variable in the last line.
另一种情况是编写一个否定测试,该测试调用带有带注释参数的函数,故意传递错误的参数,以测试在这种情况下是否抛出异常.为了编译这样的测试,必须有一种方法来抑制注释检查.
The other case is to write a negative test that calls a function with annotated parameter intentionally passing the wrong parameter in order to test that the Exception is thrown in such case. There must be a way to suppress annotation check in order to compile such test.
推荐答案
我找到了抑制注释检查的方法.其实就是三个:
I've found the way to suppress the annotation checks. Actually, there are three of them:
在您的类定义之前添加
@SuppressWarnings("ResourceType")
.就我而言:
@SuppressWarnings("ResourceType")
public class MainActivity extends ActionBarActivity {
...
}
在您的方法定义之前添加 @SuppressWarnings("ResourceType")
.就我而言:
@Override
@SuppressWarnings("ResourceType")
protected void onCreate(Bundle savedInstanceState) {
...
}
这两种方法对我不起作用,因为我想对我的所有代码进行注释检查,只有一个语句除外.
These two approaches do not work for me, because I want annotation checks on all of my code, except for just one statement.
要取消对单行的检查,请添加特殊格式的注释 (!!!).
To suppress a check on a single line add a specially formatted comment (!!!).
//noinspection ResourceType
fState = savedInstanceState.getInt(BUNDLE_STATE);
这篇关于在特殊情况下如何禁用 Android @IntDef 注释检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!