使用反射不起作用改变布尔字符串值 [英] Altering Boolean string values using reflection does not work

查看:189
本文介绍了使用反射不起作用改变布尔字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是用Java反射试验和内联字符串,并与我觉得这混乱的结果出现了。

I was experimenting with Java reflection and inlined Strings and came up with the result which I find confusing.

import java.lang.reflect.Field;

public class HappyDebugging {

    public static void main(String[] args) throws Exception {
        defineTrueFalse();

        System.out.println("true is " + true); // why is it "true is true"?
        System.out.println("false is " + false);
        System.out.println(true);
        System.out.println(false);
        System.out.println("true");
        System.out.println("false");
        System.out.println("true is " + Boolean.valueOf(true));
        System.out.println("false is " + Boolean.valueOf(false));
        System.out.println("true is " + Boolean.valueOf("true"));
        System.out.println("false is " + Boolean.valueOf("false"));
    }

    static void defineTrueFalse() throws Exception{
        Field field = String.class.getDeclaredField("value");
        field.setAccessible(true);
        field.set("true", new char[] {'f', 'a', 'l', 's', 'e'});
        field.set("false", new char[] {'t', 'r', 'u', 'e'});

        field = String.class.getDeclaredField("offset");
        field.setAccessible(true);
        field.setInt("true", 0);
        field.setInt("false", 0);

        field = String.class.getDeclaredField("count");
        field.setAccessible(true);
        field.setInt("true", 5);
        field.setInt("false", 4);
    }
}

为什么前两行输出为

Why are first two lines in the output are

true is true
false is false

我希望他们能够

true is false
false is true

请注意输出在不同平台上有所不同。

Please note the output varies on different platforms.

推荐答案

在我的编译器,这两条线会被编译使用实际的字符串真实不虚假的就是假(即不运行时发生拼接),让你的反射邪恶来得太迟。你说的输出取决于平台,所以我想有些编译器不能执行该优化。

In my compiler, those two lines get compiled to use the actual strings "true is true" and "false is false" (that is, no run-time concatenation occurs), so your reflective evil comes too late. You say that the output depends on the platform, so I guess some compilers must not perform this optimization.

这篇关于使用反射不起作用改变布尔字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆