在java-8中处理或避免NPE的最佳方法是什么?

时间:2016-07-10 00:15:49

标签: exception nullpointerexception java-8

如何在java-8中避免/处理更清晰,更安全的Optional

Optional emptyOptional = Optional.empty(); emptyOptional.ifPresent(System.out::println); if (emptyOptional.isPresent()) System.out.println(emptyOptional.get()); 以外的类别:

java-8

function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(reverseGeoLookup); } else { x.innerHTML="Geolocation is not supported by this browser."; } } function reverseGeoLookup(position) { var lat = position.coords.latitude; var lon = position.coords.longitude; var txt; var req = new XMLHttpRequest() req.open("GET", "https://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=true", true) req.onreadystatechange = function() { if(req.readyState == 4) { var result = JSON.parse(req.response).results for(var i = 0, length = result.length; i < length; i++) { for(var j = 0; j < result[i].address_components.length; j++) { var component = result[i].address_components[j] if(~component.types.indexOf("postal_code")) { txt = component.long_name; $.ajax({ url: "genMapXML.php", type: "post", data: { post_code: txt }, success: function(){ alert('success'); }, error: function(){ alert('failure'); } }); document.getElementById("trace_location").innerHTML = txt; return false; } } } } } req.send() } 还有其他方法吗?

1 个答案:

答案 0 :(得分:0)

在java 8中避免!= null语句的唯一功能是可选,如果你想使用不同的模式,你几乎没有选择:

  1. Null Object Pattern
  2. 基于注释,例如JetBrains @NotNull/@Nullable。有关详情,请查看Java @NotNull
  3. 此外,您可以在SOF中查看有关avoiding-null-statements

    的答案