Hum*_*mad 4 java optional java-8
我有一个来自Github的应用程序,其中使用了Java 8 API,即Optional关键字。但是我想运行该应用程序的环境设置为JDK_7。因此,由于我对Java 8 API的使用经验为零,因此谁能提供以下示例代码的替代代码块:
public final static Optional<String> reverseGeocodeFromLatLong(final double latitude, final double longitude) {
final StringBuilder bingMapsURL = new StringBuilder();
bingMapsURL
.append(BING_MAPS_URL_START)
.append(latitude)
.append(",")
.append(longitude)
.append(BING_MAPS_URL_MIDDLE_JSON)
.append(Constants.BING_MAPS_API_KEY_VALUE);
LOGGER.debug("BingMapsURL==>{}", bingMapsURL.toString());
HttpURLConnection httpURLConnection;
InputStream inputStream = null;
try {
final URL url = new URL(bingMapsURL.toString());
httpURLConnection = (HttpURLConnection)url.openConnection();
if(HttpURLConnection.HTTP_OK == httpURLConnection.getResponseCode()){
inputStream = httpURLConnection.getInputStream();
return getStateFromJSONResponse(inputStream);
}
} catch (final Throwable throwable) {
LOGGER.error(throwable.getMessage(), throwable);
throwable.printStackTrace();
} finally{
if(null != inputStream) {
try {
inputStream.close();
} catch (final IOException ioException) {
LOGGER.error(ioException.getMessage(), ioException);
ioException.printStackTrace();
}
}
httpURLConnection = null;
}
return Optional.absent();
}
Run Code Online (Sandbox Code Playgroud)
Optional的目的是迫使您不要忘记空检查,因此您可以return Optional.absent()
用return null
和代替,并用getStateFromJSONResponse
return String
代替Optional<String>
。然后,别忘了null
在代码中检查s,因为现在您不会被迫进行检查。
归档时间: |
|
查看次数: |
3656 次 |
最近记录: |