java - Modifying / Setting a String returned from an Accessor Method -
java - Modifying / Setting a String returned from an Accessor Method -
i'm using specific api has method "getname()". getname() returns string. possible modify string? there no modifier method included in api, , string getname() returns private. cannot modify api.
contrary prevailing opinion, is possible alter contents of string object on jdk versions 1.5 , newer, (and else here) discourage many reasons. strings never meant changed, , they're not built it, meaning effort quite messy. said, if need absolute lastly resort or else world going end kind of thing, here's bare-bones way it:
public static void main(string[] args) throws exception { string foo = "foo"; system.out.println("foo's hash value: " + foo.hashcode()); field stringvaluefield = string.class.getdeclaredfield("value"); stringvaluefield.setaccessible(true); stringvaluefield.set(foo, "bar".tochararray()); field stringhashfield = string.class.getdeclaredfield("hash"); stringhashfield.setaccessible(true); stringhashfield.set(foo, 0); system.out.println("foo's new value: " + foo); system.out.println("foo's new hash value: " + foo.hashcode()); }
make careful note, however, of other fields in string: offset , count. you'll have deal fields, too, depending on how alter string's value. finally, , maybe importantly, have consider happen if modify interned string.
java string
Comments
Post a Comment