在下想通過反射來改變一個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)
首先,你可以追蹤下java的String類,真的沒有count這個屬性的啊。
其次,相信我,我找了好幾遍,真的沒有,編譯器也很無辜,真的沒有count這個屬性。
你能告訴我你是用的JDK哪個版本麼?