- public class ReflectTest {
- private volatile String name = "before";
- public void setName(String name) {
- this.name = name;
- }
- public static void main(String[] args) {
- ReflectTest test = new ReflectTest();
- try {
- System.out.println(getValue(test, "name"));
- test.setName("after");
- System.out.println(getValue(test, "name"));
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- }
- }
- public static Object getValue(Object instance, String fieldName) throws IllegalAccessException,
- NoSuchFieldException {
- Field field = getField(instance.getClass(), fieldName);
- // 参数值为true,禁用访问控制检查
- field.setAccessible(true);
- return field.get(instance);
- }
- public static Field getField(Class thisClass, String fieldName) throws NoSuchFieldException {
- if (fieldName == null) {
- throw new NoSuchFieldException("Error field !");
- }
- Field field = thisClass.getDeclaredField(fieldName);
- return field;
- }
- }
- 打印结果:
-
- before
- after