jeudi 22 octobre 2020

Tried Java reflection's ".getDeclaredField" method but still meet "NoSuchFieldException"

Hi StackOverflow community,

I was trying modification on instance's fields through Java's reflection.

Here is my original code.

        for(Field f: customerClass.getDeclaredFields()) {
            System.out.println(f);
        }
        System.out.println("\n");

        System.out.println(customerClass.getDeclaredField("firstName"));

        for(int i=0; i < columnNames.length; i++) {
            System.out.println(columnNames[i]);
            field = customerClass.getDeclaredField(columnNames[i]);
            field.setAccessible(true);

And the results.

private java.lang.String Customer.firstName
private java.lang.String Customer.lastName

private java.lang.String Customer.firstName
"firstName"
java.lang.NoSuchFieldException: "firstName"
        at java.lang.Class.getDeclaredField(Class.java:2070)

I am wondering why "customerClass.getDeclaredField("firstName")" works but "customerClass.getDeclaredField(columnNames[i])" throws an Exception, since columnNames[0] == "firstName".

This is my first question. Thank you !





Aucun commentaire:

Enregistrer un commentaire