如何将可选字段 (Java 8 API) 更改为 Java 7
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 的目的几乎是强迫你不要忘记空检查,所以你可以用 return null
替换 return Optional.absent()
并使 getStateFromJSONResponse
return String
而不是 Optional<String>
。然后不要忘记检查代码中的 null
s,因为现在您不会被迫进行检查。
我有一个取自 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 null
替换 return Optional.absent()
并使 getStateFromJSONResponse
return String
而不是 Optional<String>
。然后不要忘记检查代码中的 null
s,因为现在您不会被迫进行检查。