java - How does reflection and immutability supposed to work together -
according jsr-133 immutable objects thread safe , don't need synchronization. it's possible update values of final fields using reflection:
package com.stackoverflow; import java.lang.reflect.field; public class whatsgoingon { static class immutable { private final int value; public immutable(int value) { this.value = value; } public int getvalue() { return value; } } public static void main(string[] args) throws nosuchfieldexception, securityexception, illegalargumentexception, illegalaccessexception { final immutable immutable = new immutable(integer.min_value); final field f = immutable.class.getdeclaredfield("value"); f.setaccessible(true); system.out.println(immutable.getvalue()); f.set(immutable, integer.max_value); system.out.println(immutable.getvalue()); } }
given number of frameworks (spring , hibernate few) rely on reflection i'm curious spec says scenario. e.g. if put field update synchronized block guarantee visibility in other threads, or value cached in registers per spec final.
http://download.oracle.com/otndocs/jcp/memory_model-1.0-pfd-spec-oth-jspec/
an object considered immutable if state cannot change after constructed. http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
you using object mutable since changing state.
it true use of reflection breaks immutability defined in tutorial, since can use change non-constant final fields.
an example of reflection-resistant immutable object following:
static class immutable { // field constant, , cannot changed using reflection private final int value = integer.min_value; public int getvalue() { return value; } } public static void main(string[] args) throws nosuchfieldexception, securityexception, illegalargumentexception, illegalaccessexception { final immutable immutable = new immutable(); final field f = immutable.class.getdeclaredfield("value"); f.setaccessible(true); system.out.println(immutable.getvalue()); f.set(immutable, integer.max_value); system.out.println(immutable.getvalue()); }
in instance reflection test fail, , value remain integer.min_value
. hey, use native code or memory editor change value else.
if go far hacking reflection, might not call field final , provide methods manipulating it.
Comments
Post a Comment