如果字段是通过一堆注释操作的,有时 lint 会产生错误的警告。举个常见的例子:
@SerializedName("id") @Expose private Integer id;
field id
仅通过 gson.fromJson() 分配。这种操作对于 lint 是不可见的,因此它会抛出警告 variable id is never assigned
因此,在这种特殊情况下,我想配置 lint,以忽略检查是否曾经分配过字段,是否用 @SearializedName
注释(请不要建议原始 @SuppressWarnings("unused")
必须为每个字段手动设置,如果字段被使用,将阻止检查)
最佳答案
Gson 使用在运行时发生的反射序列化字段。 UnusedAssignment 检查发现满足以下任何条件的变量:
- the variable never gets read after assignment
- the value is always overwritten with another assignment before the next variable read
- the variable initializer is redundant (for one of the above two reasons) - the variable is never used.
消除此特定检查的警告的唯一选择是通过更新 lint.xml 或通过 @SuppressWarnings("unused")
来抑制它们。如果你真的不想做这些事情,那么可以写一个 custom Lint inspection忽略带有 @SerializedName
注释的字段。
这种方法的缺点是,如果你想在一个没有被 Gson 序列化的类中使用 @SerializedName
,如果变量未被使用,你将不再收到警告。它也比将 @SuppressWarnings("unused")
添加到 GSON 模型类的顶部要复杂得多。
关于android - 如何配置 lint 以忽略特定情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36499274/