类型不匹配:无法从StringBuilder转换为String

use*_*855 26 java android

此方法返回给定URL的源.

private static String getUrlSource(String url) {
    try {
        URL localUrl = null;
        localUrl = new URL(url);
        URLConnection conn = localUrl.openConnection();
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
        String line = "";
        String html;
        StringBuilder ma = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            ma.append(line);
        }
        return ma;
    } catch (Exception e) {
        Log.e("ERR",e.getMessage());
    }
}
Run Code Online (Sandbox Code Playgroud)

它给了我这个错误:

Type mismatch: cannot convert from StringBuilder to String
Run Code Online (Sandbox Code Playgroud)

还有两个选择:

  1. Change the return type to StringBuilder. 但我希望它返回一个字符串.
  2. Change type of ma to String. 更改String后没有append()方法.

Bac*_*ash 54

只是用

return ma.toString();
Run Code Online (Sandbox Code Playgroud)

代替

return ma;
Run Code Online (Sandbox Code Playgroud)

ma.toString() 返回StringBuilder的字符串表示形式.

有关详细信息,请参见StringBuilder#toString()

正如Valeri Atamaniouk在评论中建议的那样,你也应该在catch块中返回一些东西,否则你会得到一个编译错误missing return statement,所以编辑

} catch (Exception e) {
    Log.e("ERR",e.getMessage());
}
Run Code Online (Sandbox Code Playgroud)

} catch (Exception e) {
    Log.e("ERR",e.getMessage());
    return null; //or maybe return another string
}
Run Code Online (Sandbox Code Playgroud)

会是一个好主意.


编辑

正如Esailija所说,我们在这段代码中有三种反模式

} catch (Exception e) {           //You should catch the specific exception
    Log.e("ERR",e.getMessage());  //Don't log the exception, throw it and let the caller handle it
    return null;                  //Don't return null if it is unnecessary
}
Run Code Online (Sandbox Code Playgroud)

所以我觉得做这样的事情会更好:

private static String getUrlSource(String url) throws MalformedURLException, IOException {
    URL localUrl = null;
    localUrl = new URL(url);
    URLConnection conn = localUrl.openConnection();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
    String line = "";
    String html;
    StringBuilder ma = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        ma.append(line);
    }
    return ma.toString();
}
Run Code Online (Sandbox Code Playgroud)

然后,当你打电话给它时:

try {
    String urlSource = getUrlSource("http://www.google.com");
    //process your url source
} catch (MalformedURLException ex) {
    //your url is wrong, do some stuff here
} catch (IOException ex) {
    //I/O operations were interrupted, do some stuff here
}
Run Code Online (Sandbox Code Playgroud)

有关Java反模式的更多详细信息,请查看这些链接:

  • 吞咽异常,记录它并返回"null" - 所有3个反模式同时进行.令人印象深刻. (2认同)