How to get value of String field from Java reflection?

后端 未结 3 1841
猫巷女王i
猫巷女王i 2021-01-22 10:21

I have an object that has a String field. I can obtain this field by calling:

Field field = someObj.getClass().getField(\"strField\");

I sett a

3条回答
  •  孤城傲影
    2021-01-22 11:24

    Even without the getter or the setter methods for a property, you can change or get the value using an object reference and Java Reflection.

    import java.lang.reflect.Field;
    
    public class Bean {
    
        private String strField;
    
        public static void main(String[] args) throws Exception {
            Bean bean = new Bean();
            Field field = bean.getClass().getDeclaredField("strField");
            field.set(bean, "Hello");
            System.out.println(field.get(bean));
        }
    
    }
    

提交回复
热议问题