使用反射更改字符串的效果 [英] effect of changing String using reflection

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

问题描述

众所周知,String在java中是不可变的。但是,可以通过获取Field并设置访问级别来使用反射来更改它。 (我知道这是未经修改的,我不打算这样做,这个问题纯粹是理论上的)。

As we all know, String is immutable in java. however, one can change it using reflection, by getting the Field and setting access level. (I know it is unadvised, I am not planning to do so, this question is pure theoretical).

我的问题:假设我知道自己在做什么(并根据需要修改所有字段),程序是否会正常运行?或者jvm是否进行了一些依赖于String不可变的优化?我会遭受性能损失吗?如果是这样,它会做出什么假设?该计划会出现什么问题

my question: assuming I know what I am doing (and modify all fields as needed), will the program run properly? or does the jvm makes some optimizations that rely on String being immutable? will I suffer performance loss? if so, what assumption does it make? what will go wrong in the program

p.s。字符串只是一个例子,除了示例之外,我对一般答案感兴趣。

p.s. String is just an example, I am interested actually in a general answer, in addition to the example.

谢谢!

推荐答案

如果你这样做,你肯定会遇到麻烦。这是否意味着你肯定会立即看到错误?不会。你可能会在很多情况下侥幸逃脱,取决于你正在做什么。

You are definitely asking for trouble if you do this. Does that mean you will definitely see bugs right away? No. You might get away with it in a lot of cases, depending on what you're doing.

以下几种情况会让你感到厌烦:

Here are a couple of cases where it would bite you:


  • 修改一个恰好在代码中某处声明为字面值的字符串。例如,你有一个函数,并在某处调用它,如函数(Bob);在这种情况下,字符串Bob在整个应用程序中更改 (对于声明的字符串常量也是如此] as final )。

  • 修改子字符串操作中使用的字符串,或者是子字符串操作的结果。在Java中,获取字符串的子字符串实际上使用与源字符串相同的基础字符数组,这意味着对源字符串的修改将影响子字符串(反之亦然)。

  • 您修改恰好在某个地方用作地图中的键的字符串。它将不再等于其原始值,因此查找将失败。

  • You modify a string that happens to have been declared as literal somewhere within the code. For example you have a function and somewhere it is being called like function("Bob"); in this scenario the string "Bob" is changed throughout your app (this will also be true of string constants declared as final).
  • You modify a string which is used in substring operations, or which is the result of a substring operation. In Java, taking a substring of a string actually uses the same underlying character array as the source string, which means modifications to the source string will affect substrings (and vice versa).
  • You modify a string that happens to be used as a key in a map somewhere. It will no longer compare equal to its original value, so lookups will fail.

我知道这个问题是关于Java的,但我< a href =http://philosopherdeveloper.com/posts/are-strings-really-immutable-in-net.html =nofollow>写了一篇博客文章,然后回顾说明你是多么疯狂如果你在.NET中改变一个字符串,程序可能会表现。情况非常相似。

I know this question is about Java, but I wrote a blog post a while back illustrating just how insane your program may behave if you mutate a string in .NET. The situations are really quite similar.

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

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