我有一个从 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 的目的几乎是强制您不要忘记空检查,因此您可以替换 return Optional.absent()
与 return null
并制作getStateFromJSONResponse
返回 String
而不是 Optional<String>
.然后不要忘记检查 null
s 在您的代码中,因为现在您不会被迫进行检查。
关于java - 如何将可选字段(Java 8 API)更改为 Java 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31781449/