Java NoSuchFieldError when using Reflection

怎甘沉沦 提交于 2021-01-28 06:41:50

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/15866993/java-nosuchfielderror-when-using-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!