我刚刚编写了这段代码,以便更好地理解反射。
这是ReflectionTestMain类:
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectionTestMain {
public static void main(String[] args) {
try {
ReflectionTest rt = new ReflectionTest();
Class<ReflectionTest> c = ReflectionTest.class;
Field f = c.getDeclaredField("value");
f.setAccessible(true);
f.set(rt, "text");
Method m = c.getDeclaredMethod("getValue");
m.setAccessible(true);
String value = (String) m.invoke(rt);
System.out.println(value);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
这是ReflectionTest类。
public class ReflectionTest {
private final String value = "test";
private String getValue() {
return value;
}
}
这段代码输出了“test”,但我预期它应该输出“text”。这是什么原因导致它不能正常工作,我该如何修复?