众所周知, 在Java中, String类是不可变的。那么到底什么是不可变的对象呢? 可以这样认为:如果一个对象,在它创建完成之后,不能再改变它的状态,那么这个对象就是不可变的。不能改变状态的意思是,不能改变对象内的成员变量,包括基本数据类型的值不能改变,引用类型的变量不能指向其他的对象,引用类型指向的对象的状态也不能改变。
1
2
3
4
5
6
7
|
String s =
"ABCabc"
;
System.out.println(
"s = "
+ s);
s =
"123456"
;
System.out.println(
"s = "
+ s);
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public
final
class
String
implements
java.io.Serializable, Comparable<string>, CharSequence
{
/** The value is used for character storage. */
private
final
char
value[];
/** The offset is the first index of the storage that is used. */
private
final
int
offset;
/** The count is the number of characters in the String. */
private
final
int
count;
/** Cache the hash code for the string */
private
int
hash;
// Default to 0</string>
|
1
2
3
4
5
6
7
|
public
final
class
String
implements
java.io.Serializable, Comparable<string>, CharSequence {
/** The value is used for character storage. */
private
final
char
value[];
/** Cache the hash code for the string */
private
int
hash;
// Default to 0</string>
|
1
2
3
4
5
6
|
String a =
"ABCabc"
;
System.out.println(
"a = "
+ a);
a = a.replace(
'A'
,
'a'
);
System.out.println(
"a = "
+ a);
|
1
2
3
4
5
6
7
|
String ss =
"123456"
;
System.out.println(
"ss = "
+ ss);
ss.replace(
'1'
,
'0'
);
System.out.println(
"ss = "
+ ss);
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public
static
void
testReflection()
throws
Exception {
//创建字符串"Hello World", 并赋给引用s
String s =
"Hello World"
;
System.out.println(
"s = "
+ s);
//Hello World
//获取String类中的value字段
Field valueFieldOfString = String.
class
.getDeclaredField(
"value"
);
//改变value属性的访问权限
valueFieldOfString.setAccessible(
true
);
//获取s对象上的value属性的值
char
[] value = (
char
[]) valueFieldOfString.get(s);
//改变value所引用的数组中的第5个字符
value[
5
] =
'_'
;
System.out.println(
"s = "
+ s);
//Hello_World
}
|