gpt4 book ai didi

java - 一个简单的 Java 代码,运行良好但运行方式有点难以理解

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:10:56 24 4
gpt4 key购买 nike

下面的简单 Java 程序似乎通过语句 System.out.println("Hello World"); 显示字符串 Hello World,但实际上并没有。它只是将其替换为另一个字符串,在本例中为 Good Day !! 并将其显示在控制台上。字符串 Hello World 根本不显示。让我们看一下以下简单的 Java 代码片段。

package goodday;

import java.lang.reflect.Field;

final public class Main
{
public static void main(String[] args)
{
System.out.println("Hello World");
}

static
{
try
{
Field value = String.class.getDeclaredField("value");
value.setAccessible(true);
value.set("Hello World", value.get("Good Day !!"));
}
catch (Exception e)
{
throw new AssertionError(e);
}
}
}

这里只有一个关于这段代码的问题。它完全按预期工作,但我无法减少字符串 Good Day !! 的长度。如果尝试这样做,则会导致 java.lang.ArrayIndexOutOfBoudsException。如果长度增加,程序运行良好,但显示字符串中的其余字符被截断,这意味着两个字符串的长度应该有些相同。为什么?这是我无法理解的事情。

最佳答案

value 字段是一个 char[],它在内部存储字符串用作其后备存储的字符数组。其他字段指示字符数组的初始偏移量和字符串的长度。 (所以要获取一个子字符串,它只是创建一个新的 String 对象,该对象引用相同的 char[] 但具有不同的起始偏移量和长度。)

如果您也修改这些字段,您可以对字符串做任何您想做的事情。示例:

import java.lang.reflect.Field;

public class Test
{
// Obviously in real code you wouldn't use Exception like this...
// Although hacking string values with reflection is worse, of course.
public static void main(String[] args) throws Exception
{
System.out.println("Hello World");
replaceHelloWorld("Goodbye!");
System.out.println("Hello World");
replaceHelloWorld("Hello again!");
System.out.println("Hello World");
}

static void replaceHelloWorld(String text) throws Exception
{
// Note: would probably want to do hash as well...
copyField(text, "Hello World", "value");
copyField(text, "Hello World", "offset");
copyField(text, "Hello World", "count");
}

static void copyField(String source, String target, String name)
throws Exception
{
Field field = String.class.getDeclaredField(name);
field.setAccessible(true);
field.set(target, field.get(source));
}
}

关于java - 一个简单的 Java 代码,运行良好但运行方式有点难以理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8086065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com