如何将可选字段(Java 8 API)更改为Java 7

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)

Sim*_*mon 5

Optional的目的是迫使您不要忘记空检查,因此您可以return Optional.absent()return null和代替,并用getStateFromJSONResponsereturn String代替Optional<String>。然后,别忘了null在代码中检查s,因为现在您不会被迫进行检查。