Éviter NullPointer Exception en Java

Mots clés : javanullpointerexceptionjava

meilleur 4 Réponses Éviter NullPointer Exception en Java

vote vote

92

assert <condition> 
assert <condition> : <object> 
public interface Action {   void doSomething(); }  public interface Parser {   Action findAction(String userInput); } 
public class MyParser implements Parser {   private static Action DO_NOTHING = new Action() {     public void doSomething() { /* do nothing */ }   };    public Action findAction(String userInput) {     // ...     if ( /* we can't find any actions */ ) {       return DO_NOTHING;     }   } } 
Parser parser = ParserFactory.getParser(); if (parser == null) {   // now what?   // this would be an example of where null isn't (or shouldn't be) a valid response } Action action = parser.findAction(someInput); if (action == null) {   // do nothing } else {   action.doSomething(); } 
ParserFactory.getParser().findAction(someInput).doSomething(); 
try {     ParserFactory.getParser().findAction(someInput).doSomething(); } catch(ActionNotFoundException anfe) {     userConsole.err(anfe.getMessage()); } 
public Action findAction(final String userInput) {     /* Code to return requested Action if found */     return new Action() {         public void doSomething() {             userConsole.err("Action not found: " + userInput);         }     } } 
vote vote

89

@NotNull public static String helloWorld() {     return "Hello World"; } 
@Nullable public static String helloWorld() {     return "Hello World"; } 
public static void main(String[] args) {     String result = helloWorld();     if(result != null) {         System.out.println(result);     } } 
void someMethod(@NotNull someParameter) { } 
someMethod(null); 
@Nullable iWantToDestroyEverything() { return null; } 
iWantToDestroyEverything().something(); 
vote vote

75

public void method(Object object) {   if (object == null) {     throw new IllegalArgumentException("...");   } 
public String getFirst3Chars(String text) {   return text.subString(0, 3); } 
if (object == null) {   // something } else {   // something else } 
vote vote

68

public String getPostcode(Person person) {     return person?.getAddress()?.getPostcode();   }   

Questions similaires