class_brick
2016-04-16 17:58
采纳率: 100%
浏览 1.4k
已采纳

新人学习java反射时的问题

在下想通过反射来改变一个String对象中的count变量,但是报错里面说String没有count变量,在网上查了一点资料发现String是有一个私有变量count的,在下在此求教大神解答,不胜感激
package dear_brick;

import java.lang.reflect.Field;

public class dear {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException{
dear brick;
final String str = "brick";
dear.changeStringValue(str);
dear.changeStringCount(str,3);
System.out.println(str);
System.out.println(str.length());
}

public static void changeStringValue(String str) throws ClassNotFoundException,NoSuchFieldException,IllegalAccessException{
    String name = str.getClass().getName();
    Class clazz = Class.forName(name);
    Field field = clazz.getDeclaredField("value");
    field.setAccessible(true);
    Object object = field.get(str);
    char[] obj_value = new char[6];
    for(int i = 0; i<6; i++){
        obj_value[i] = '6';
    }
    field.set(str,obj_value);
}

public static void changeStringCount(String str,int count) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
    String class_name = str.getClass().getName();
    Class clazz = Class.forName(class_name);
    Field field = clazz.getDeclaredField("count");
    field.setAccessible(true);
    Object object = field.get(str);
    field.set(str, count);
}

}
错误信息:
Exception in thread "main" java.lang.NoSuchFieldException: count
at java.lang.Class.getDeclaredField(Class.java:2070)
at dear_brick.dear.changeStringCount(dear.java:31)
at dear_brick.dear.main(dear.java:10)

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题