title: How do I ensure a Java Object is of type Map<String, Object>
body: <p>Short, at-a-glance summary of question (TLDR): how do I ensure a Java <code>Object</code> is of type <code>Map&lt;String, Object&gt;</code>?</p>
  
  <hr>
  
  <p>I have a YAML document as a <code>String</code>. I create the YAML using SnakeYAML from a <code>Map&lt;String, Object&gt;</code> but it could be tampered with before I read it back again. I don't want to resort to PKI signing, it's enough to see whether the YAML representation is still a <code>Map&lt;String, Object&gt;</code>, even if the <code>Object</code> values may be all over the place. I care about <em>type</em>, not content.</p>
  
  <p>So: how do I ensure an <code>Object</code> is indeed of type <code>Map&lt;String, Object&gt;</code>?</p>
  
  <p>Here's how I am trying to circumvent the various SuppressWarnings of type erasure:</p>
  
  <pre><code>Object yamlObject = yaml.load(someYamlDocumentAsString);
  // I only want to proceed if this YAML object is a Map&lt;String, Object&gt;
  if ((yamlObject instanceof Map&lt;?, ?&gt;)) {
    Map&lt;?, ?&gt; propertyMap = (Map&lt;?, ?&gt;) yamlObject;
    for (Entry&lt;?, ?&gt; propertyEntry : propertyMap.entrySet()) {
      // I am checking each key and throwing if it's not a "String"
      Object propertyKey = propertyEntry.getKey();
      if (!(propertyKey instanceof CharSequence)) {
        throw new BananaException("FIXME"); // FIXME
      }
    }
  } else {
    throw new CoconutException("FIXME"); // FIXME
  }
  </code></pre>
  
  <h2>Can the above be done better?</h2>
  
  <p>Incidentally, I don't suppose Java has something akin to C#'s <code>as</code> keyword (from MSDN: The <code>as</code> operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception.)?</p>
  
  <hr>
  
  <p>After the code above, can I safely suppress warnings for this:</p>
  
  <pre><code>@SuppressWarnings("unchecked")
  Map&lt;String, Object&gt; aBeautifulAndCozyMap = (Map&lt;String, Object&gt;) propertyMap;
  </code></pre>