我是 Java 新手,我在这里看到了一个问答部分,其中包含两个删除可变性的示例。在测试MutableString.java 时:
import java.lang.reflect.Field;
public class MutableString {
public static void main(String[] args) {
String s = "Immutable";
String t = "Notreally";
mutate(s, t);
StdOut.println(t);
// strings are interned so this doesn't even print "Immutable" (!)
StdOut.println("Immutable");
}
// change the first min(|s|, |t|) characters of s to t
public static void mutate(String s, String t) {
try {
Field val = String.class.getDeclaredField("value");
Field off = String.class.getDeclaredField("offset");
val.setAccessible(true);
off.setAccessible(true);
int offset = off.getInt(s);
char[] value = (char[]) val.get(s);
for (int i = 0; i < Math.min(s.length(), t.length()); i++)
value[offset + i] = t.charAt(i);
}
catch (Exception e) { e.printStackTrace(); }
}
}
我收到以下错误:
java.lang.NoSuchFieldException: offset
任何关于以下内容的输入将不胜感激:
a)为什么会出现此异常
b)如何检查类中存在哪些字段(特别是 Java 字符串)