根据我从该主题收集的信息,我认为异常表示它不知道ClassB中的测试"是什么,并且我还没有在ClassB中对其进行初始化,但是我真的无法弄清楚.解决方案 String [].class.getField("test")引发 NoSuchFieldException ,因为此字段确实 String [] 中不存在,而在 packageA.ClassA 中存在. ClassA.class.getField("test")将返回正确的字段访问.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: testat 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. 这篇关于使用反射时的Java NoSuchFieldError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-04 20:52