Note that there are some explanatory texts on larger screens.

plurals
  1. POModifying final fields in Java
    primarykey
    data
    text
    <p>Let's start with a simple test case:</p> <pre><code>import java.lang.reflect.Field; public class Test { private final int primitiveInt = 42; private final Integer wrappedInt = 42; private final String stringValue = "42"; public int getPrimitiveInt() { return this.primitiveInt; } public int getWrappedInt() { return this.wrappedInt; } public String getStringValue() { return this.stringValue; } public void changeField(String name, Object value) throws IllegalAccessException, NoSuchFieldException { Field field = Test.class.getDeclaredField(name); field.setAccessible(true); field.set(this, value); System.out.println("reflection: " + name + " = " + field.get(this)); } public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException { Test test = new Test(); test.changeField("primitiveInt", 84); System.out.println("direct: primitiveInt = " + test.getPrimitiveInt()); test.changeField("wrappedInt", 84); System.out.println("direct: wrappedInt = " + test.getWrappedInt()); test.changeField("stringValue", "84"); System.out.println("direct: stringValue = " + test.getStringValue()); } } </code></pre> <p>Anybody care to guess what will be printed as output (shown at the bottom as to not spoil the surprise immediately).</p> <p>The questions are:</p> <ol> <li>Why do primitive and wrapped integer behave differently?</li> <li>Why does reflective vs direct access return different results?</li> <li>The one that plagues me most - why does String behave like primitive <code>int</code> and not like <code>Integer</code>?</li> </ol> <p>Results (java 1.5):</p> <pre><code>reflection: primitiveInt = 84 direct: primitiveInt = 42 reflection: wrappedInt = 84 direct: wrappedInt = 84 reflection: stringValue = 84 direct: stringValue = 42 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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