今天在朋友的提醒下遇到一个很有趣的面试题,如下
public class test {
public static void main(String[] args){
String str = "hello";
fun(str);
// 实现打印 hello world!
System.out.println(str);
}
public static void fun(String str){
//这里写出你的实现方法...
}
}
初步分析,fun方法没有返回值,这就意味着必须修改str的实际变量
public static void fun(String str){
//尝试直接追加字符串
str+= " world!";
//打印: hello world!
System.out.println(str);
}
尝试直接追加,在fun方法里打印也是正常的,但是回到main方法打印的还是“hello”,这是什么情况?
分析可能是在fun方法里,str已经不是原来的引用,这里验证一下
public static void fun(String str){
//存放输入的原始引用地址
String s1=str;
str+= " world!";
System.out.println(str);
//打印: false, 意味着str本身已经不是原来的str
System.out.println(s1==str);
}
查看String.class
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
...
可以观察到String对象的值是由类中的char数组决定的,而该属性又被private和final修饰,因此必须使用反射才能修改
使用反射代码如下(异常也可捕获而不必向上抛出)
public static void fun(String str) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
// 通过实例获取到Class类对象
Class clazz = str.getClass();
// 先把Class类对象所有的属性输出,最后找到应该是value存放了信息
// Field[] fs = clazz.getDeclaredFields();
// for (Field f : fs) {
// System.out.println(f);
// }
// 获取到属性对象
Field field = clazz.getDeclaredField("value");
// System.out.println(field);
// value实际上是char[]数组,因此字符串追加后转一下
char[] cs2 = (str.toString()+" world!").toCharArray();
// 暴力反射,使得权限为private属性可以修改
field.setAccessible(true);
//设置对象的对应值,set(Object target,Object value)
field.set(str,cs2);
}
修改成功
PS:经过测试,当类中属性被private 或 final修饰时,要想修改只能通过反射