[英]How to change Optional field(Java 8 API) into Java 7
我从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();
}
Optional的目的几乎是强迫你不要忘记null检查,所以你可以用return null
替换return Optional.absent()
,并使getStateFromJSONResponse
返回一个String
而不是Optional<String>
。 然后不要忘记检查代码中的null
,因为现在您不会被迫进行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.