未经检查的 cast Map <String, String> allPreferences

unchecked cast Map <String, String> allPreferences

我有一个关于未经检查的转换的 gradle 警告。该应用程序构建时没有错误,但我想清理所有代码问题。我在这里看到了类似的 post How do I cast from int to generic type Integer?

我不清楚如何检查转换的值。

.../mayday/md/model/SMSSettings.java:56: warning: [unchecked] unchecked cast
        Map<String, String> allPreferences = (Map<String, String>) sharedPreferences.getAll();
                                                                                           ^
  required: Map<String,String>
  found:    Map<String,CAP#1>
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Object from capture of ?

第 56 行 Map<String, String> allPreferences = (Map<String, String>) sharedPreferences.getAll();

public static SMSSettings retrieve(Context context) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    Map<String, String> allPreferences = (Map<String, String>) sharedPreferences.getAll();
    List<String> retrievedPhoneNumbers = retrievePhoneNumbers(allPreferences);
    return new SMSSettings(retrievedPhoneNumbers, allPreferences.get(SMS_MESSAGE));
}

getAll returns a Map<String, ?> 而不是 Map<String, String>,其中无限通配符 ?<? extends Object> 的简短版本。如果我没误会你的话

 Map<String, ?> allPreferences = sharedPreferences.getAll();

应该删除警告

请注意,SharedPreferences can contain different objects than just Strings 如果您 100% 确定您的 SharedPreferences 对象中只有字符串,您可以忽略此警告并将 @SuppressWarnings("unchecked") 添加到您的方法或上面的转换行。