简体   繁体   中英

Java NoSuchFieldError when using Reflection

I'm trying to modify a public static final String[] field I made in ClassA, and then modify it in ClassB using reflection. However I get a NoSuchFieldException.

java.lang.NoSuchFieldException: test
at java.lang.Class.getField(Unknown Source)
at packageA.ClassA.<init>(ClassA.java:17)

ClassA is located in packageA and ClassB is located in packageB if that matters.

Class A , creates the field and calls ClassB :

package packageA;

import packageB.ClassB;

public class ClassA {
    // Create final String[]
    public static final String[] test = new String[] {"Test1", "Test2", "Test3"};

    public ClassA() {
        // Output array content before change
        for (int i = 0; i < test.length; i++) {
            System.out.println(test[i]);
        }

        // Change array content
        try {
            new ClassB(String[].class.getField("test"), new String[] {"Change1", "Change2", "Change3"});
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Output array content after change
        for (int i = 0; i < test.length; i++) {
            System.out.println(test[i]);
        } 
    }
}

Class B, Modifies the 'test' array:

package packageB;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class ClassB {

    public ClassB(Field field, Object newValue) {
        try {
            field.setAccessible(true);

            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

            field.set(null, newValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Note: I got ClassB from here and I also saw this post but I couldn't find anything that worked.

From what i've gathered from that topic, I think the exception means that it doesn't know what 'test' is in ClassB and that I haven't initialized it in ClassB, but I couldn't really figure that out.

String[].class.getField("test") throws a NoSuchFieldException because this field does not exist in String[] , it exists in packageA.ClassA .

ClassA.class.getField("test") will return the correct field access.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM