title: java @Nonnull annotation in a method that returns null
body: <p>I have a method that gets something from a hashmap, a simplified example (that doesn't make much sense but is good enough for now) is:</p>
  
  <pre><code>private Map&lt;String,String&gt; map = new HashMap&lt;String,String&gt;();
  
  public String get(String key) {
      return map.get(key);
  }
  </code></pre>
  
  <p>This method can return a null when an entry doesn't exist for a given key obviously. The thing is, I want to annotate this method with <code>@NonNull</code> (because it is used in a gazillion places and I don't like Intellij spamming me with inspection warnings about producing a NPE and I don't want to turn off that inspection, and I also don't want to check whether the value returned is different than null everywhere I call this method. This is because I always use this method with a bunch of keys that are ALWAYS in the map. So due to the program logic this method is bound to return a <code>@NonNull</code> value.</p>
  
  <p>I am tempted to just annotate it with a <code>@NonNull</code>, but who knows someone may call it with something other than the defined keys somewhere and actually cause a NullPointerException.
  What would you do? An assertion sounds tempting to me.. Or would you just change the method to throw a RuntimException ? Or an AssertionError?</p>
  
  <p>Thanks.</p>
  
  <p>Edit:</p>
  
  <p>here's the actual implementation:</p>
  
  <pre><code>/**
   * Typesafe heterogeneous container pattern - implementation
   */
  public class HandlersMap {
  
      private final Map&lt;Class&lt;? extends TableHandler&gt;, TableHandler&gt; handlers;
  
      public HandlersMap() {
          handlers = new HashMap&lt;Class&lt;? extends TableHandler&gt;, TableHandler&gt;();
          putHandler(RolesTableHandler.class, new RolesTableHandler());
          putHandler(UsersTableHandler.class, new UsersTableHandler());
          putHandler(DevicesTableHandler.class, new DevicesTableHandler());
      }
  
      private &lt;T extends TableHandler&gt; void putHandler(@NonNull final Class&lt;T&gt; type, @NonNull final T instance) {
          handlers.put(type, type.cast(instance));
      }
  
      @NonNull
      public &lt;T extends TableHandler&gt; T getHandler(@NonNull final Class&lt;T&gt; type) {
          assert handlers.get(type) != null;
          return type.cast(handlers.get(type));
      }
  
      public Collection&lt;TableHandler&gt; values() {
          return handlers.values();
      }
  
      public int size() {
          return handlers.size();
      }
  
      public Map&lt;Class&lt;? extends TableHandler&gt;, TableHandler&gt; getMap() {
          return this.handlers;
      }
  
  }
  </code></pre>