Java String Mutability - java.lang.NoSuchFieldException: offset

我的未来我决定 提交于 2019-12-05 19:10:33

Disclaimer: these kinds of hacks are interesting lessons in learning and fun trivia. But they are definitely not something that you want to use in any production code. It will lead to pain.

By their very nature, such a hack always depends on implementation details of the classes that are hacked.

In your case you seem to be using a String implementation that doesn't have an offset field, but uses some other mechanism (or maybe just a different name!).

For example, I've just reviewed the Oracle Java 7 String class and it no longer has the offset field (which was used in Java 6 and earlier to share the char[] among substrings)!*

You can use Class.getDeclaredFields() to check which fields this implementation does define:

for (Field f : String.class.getDeclaredFields()) {
  System.out.println(f);
}

For a version of that hack that works with Java 7, you could do this:

public static void mutate(String s, String t) {
    try {
        Field val = String.class.getDeclaredField("value"); 
        val.setAccessible(true); 
        char[] value = (char[]) val.get(s); 
        for (int i = 0; i < Math.min(s.length(), t.length()); i++)
            value[i] = t.charAt(i); 
    } 
    catch (Exception e) { e.printStackTrace(); }
} 

Of course, this too will break if the internals of String change again.

* Here's an Email that talks about that change, it seems that the sharing of the char[] only lead to improved performance in a few, special cases.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!