import java.lang.reflect.Field;
public class ReflectGetFields {
public void modeString() throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException{
ReflectionPoint rp = new ReflectionPoint(1,2);
Field[] fields = rp.getClass().getFields();
System.out.println(fields);
for (int i = 0; i < fields.length; i++) {
if(fields[i].get(rp)==Class.forName("java.lang.String"));
{
String sss = (String) fields[i].get(rp);
StringBuilder strb = new StringBuilder(sss);
for (int a=0;i<strb.length();i++) {
if (strb.charAt(a)=='b') {
strb.setCharAt(a, 'a');
}
}
}
}
System.out.println(rp.toString());
}
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
ReflectGetFields rgf = new ReflectGetFields();
rgf.modeString();
}
}
Eclipse说:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at com.github.user3301.Reflection.ReflectGetFields.modeString(ReflectGetFields.java:11)
at com.github.user3301.Reflection.ReflectGetFields.main(ReflectGetFields.java:36)
我只是不知道我在哪里做错了,因为字段[i] .get(rp)返回类中的一个字段,并且有一个if语句来检查它是否是String类型,为什么它不能是强制转换为String类型?