0
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 says :

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 just don't know where did I do wrong as fields[i].get(rp) returns a field in the class and there is a if statement to check if it is a String type, so why it cannot be cast into a String type?

User3301
  • 95
  • 3
  • 8
  • share code for ReflectionPoint – Darshan Apr 01 '17 at 04:44
  • 1
    Hint: how to compare strings is a superbasic thing. You don't know how to do that. But then you want to use reflection? Not a good idea... – GhostCat Apr 01 '17 at 04:48
  • And: and don't compare class names. Class has methods like isAssignableFrom() which you should be using instead. – GhostCat Apr 01 '17 at 04:49
  • You can imagine ReflectionPoint class as a class contains some String type member variables, I've tried compare String types using fields[i].getType()==String.class and it worked, but im still puzzled fields[i].get(rp)==Class.forName("java.lang.String") did not work? – User3301 Apr 01 '17 at 07:30

0 Answers0