How to get value of String field from Java reflection?

后端 未结 3 1842
猫巷女王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:20

    if you are using java.lang.reflect.Field, the "setter" is Field.set(Object,Object) and the "getter" is Field.get(Object). in both cases, the first parameter is the instance on which you want to access the field.

    0 讨论(0)
  • 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));
        }
    
    }
    
    0 讨论(0)
  • 2021-01-22 11:24

    Easiest way is to use BeanUtils:

    String s = BeanUtils.getProperty(someObj, "strField");
    

    Note that BeanUtils will attempt to convert your property into string. You need to have a getter and setter of the property

    0 讨论(0)
提交回复
热议问题