title: Reflection generic get field value
body: <p>I am trying to obtain a field's value via reflection. The problem is I don't know the field's type and have to decide it while getting the value.</p>
  <p>This code results with this exception:</p>
  <blockquote>
  <p>Can not set java.lang.String field com....fieldName to java.lang.String</p>
  </blockquote>
  <pre class="lang-java prettyprint-override"><code>Field field = object.getClass().getDeclaredField(fieldName);
  field.setAccessible(true);
          
  Class&lt;?&gt; targetType = field.getType();
  Object objectValue = targetType.newInstance();
  
  Object value = field.get(objectValue);
  </code></pre>
  <p>I tried to cast, but I get compilation errors:</p>
  <pre><code>field.get((targetType)objectValue)
  </code></pre>
  <p>or</p>
  <pre><code>targetType objectValue = targetType.newInstance();
  </code></pre>
  <p>How can I do this?</p>