消除Android中代码警告

一、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

public static <T> T convert(Object obj, Class<T> clazz) {
    if(clazz.isInstance(obj)) {
        return clazz.cast(obj);
    } else {
        return null;
    }
}

        对于一个List来说

    public static <T> List<T> castList(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }

        对于map  

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文件中声明,然后引用

未完待续……

猜你喜欢

转载自blog.csdn.net/weixin_42277946/article/details/130672262
今日推荐