消除Android中代码警告

谁借莪1个温暖的怀抱¢ 2024-03-22 16:45 194阅读 0赞

一、Raw use of parameterized class ‘xxxx‘

原因:泛型使用了原生态类型,会导致丢失类型安全性

解决:在类后面加上对应泛型

二、Condition ‘xxxx’ is always ‘true’

原因:ide推断出这条语句永远为true,就没有必要存在

解决:删除该语句

三、Typo: In word ‘xxxx’

原因:命名没有按照标准的驼峰命名法

解决:采用驼峰命名法

四、Field can be converted to a local variable

原因:这个变量可以使用局部变量替换不用全局定义,建议删除并写成局部变量。

解决:把全局变量删除,在使用的地方定义即可

五、Lambda can be replaced with method reference

原因:lambda可以替换为方法引用

解决:用::代替方法引用

六、Unchecked cast: ‘xxxx’ to ‘xxxx’

原因:在进行类型转换时,对不确定转换后的类型进行转换

解决:使用泛型边界进行限制

举例:

如果要将一个Object类型的变量转换为指定的泛型类型T

  1. public static <T> T convert(Object obj, Class<T> clazz) {
  2. if(clazz.isInstance(obj)) {
  3. return clazz.cast(obj);
  4. } else {
  5. return null;
  6. }
  7. }

对于一个List来说

  1. public static <T> List<T> castList(Object obj, Class<T> clazz) {
  2. List<T> result = new ArrayList<>();
  3. if (obj instanceof List<?>) {
  4. for (Object o : (List<?>) obj) {
  5. result.add(clazz.cast(o));
  6. }
  7. return result;
  8. }
  9. return null;
  10. }

对于map

  1. Map<?, ?> map = (Map<?, ?>) data;

七、Unchecked call to ‘xxxx” as a member of raw type ‘’xxxx”

原因:未经检查

解决:

八、It will always be more efficient to use more specific change events if you can. Rely on notifyDataSetChanged as a last resort.

原因:在使用一个适配器的时候,使用一个更加具体的改变事件来获取更高的效率,把notifyDataSetChanged() 作为最后的使用手段.

notifyItemChanged(int)
notifyItemInserted(int)
notifyItemRemoved(int)
notifyItemRangeChanged(int, int)
notifyItemRangeInserted(int, int)
notifyItemRangeRemoved(int, int)

九、Argument ‘xxx’ might be null

原因:参数可能为空

十、Do not concatenate text displayed with setText. Use resource string with placeholders.

应该使用资源字符串来显示文本占位符,与在xml布局中直接写汉字的警告是一个意思。字符串拼接也好,直接写的汉字也好,都应该在strings.xml文件中声明,然后引用

未完待续……

发表评论

表情:
评论列表 (有 0 条评论,194人围观)

还没有评论,来说两句吧...

相关阅读