title: Java introspection: object to map
body: <p>I have a Java object <code>obj</code> that has attributes <code>obj.attr1</code>, <code>obj.attr2</code> etc. The attributes are possibly accessed through an extra level of indirection: <code>obj.getAttr1()</code>, <code>obj.getAttr2()</code>, if not public.</p>
  
  <p><strong>The challenge</strong>: I want a function that takes an object, and returns a <code>Map&lt;String, Object&gt;</code>, where the keys are strings <code>"attr1"</code>, <code>"attr2"</code> etc. and values are the corresponding objects <code>obj.attr1</code>, <code>obj.attr2</code>.
  I imagine the function would be invoked with something like </p>
  
  <ul>
  <li><code>toMap(obj)</code>,</li>
  <li>or <code>toMap(obj, "attr1", "attr3")</code> (where <code>attr1</code> and <code>attr3</code> are a subset of <code>obj</code>'s attributes), </li>
  <li>or perhaps <code>toMap(obj, "getAttr1", "getAttr3")</code> if necessary.</li>
  </ul>
  
  <p>I don't know much about Java's introspection: how do you do that in Java? </p>
  
  <p>Right now, I have a specialized <code>toMap()</code> implementation for each object type that I care about, and it's too much boilerplate.</p>
  
  <hr>
  
  <p><strong>NOTE</strong>: for those who know Python, I want something like <code>obj.__dict__</code>. Or <code>dict((attr, obj.__getattribute__(attr)) for attr in attr_list)</code> for the subset variant.</p>