Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In order to access private fields, you need to get them from the class's <em>declared</em> fields and then make them accessible:</p> <pre><code>Field f = obj.getClass().getDeclaredField("stuffIWant"); //NoSuchFieldException f.setAccessible(true); Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException </code></pre> <p><strong>EDIT</strong>: as has been commented by <em>aperkins</em>, both accessing the field, setting it as accessible and retrieving the value will all throw <code>Exception</code>s, although the only <em>checked</em> exceptions you need to be mindful of are commented above.</p> <p>The <code>NoSuchFieldException</code> would be thrown if you asked for a field by a name which did not correspond to a declared field. </p> <pre><code>obj.getClass().getDeclaredField("misspelled"); //will throw NoSuchFieldException </code></pre> <p>The <code>IllegalAccessException</code> would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the <code>f.setAccessible(true)</code> line.</p> <p>The <code>RuntimeException</code>s which may be thrown are either <code>SecurityException</code>s (if the JVM's <code>SecurityManager</code> will not allow you to change a field's accessibility), or <code>IllegalArgumentException</code>s, if you try and access the field on an object not of the field's class's type:</p> <pre><code>f.get("BOB"); //will throw IllegalArgumentException, as String is of the wrong type </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload