2

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 Field#set(Object) method, for setting the value of this instance's field, but the respective getter seems to be Field#get(Object), which is weird because I would have expected it to be Field#get().

How do I obtain the value of the instance's strField?

0

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh, he's really probably talking about java.lang.reflect.Field. Good catch!
@acdcjunior question was flagged with reflection tag so java.lang.reflect is first thing that comes in mind (at least for me :D). What was your other guess?
@Pshemo Yeah, I brain farted. I thought Field was the class of someObj and the setters for Field.strField were Field.set(Object) and Field.get(Object). His writing of Field#set(Object) (and not set(Obj,Obj)) made me completely misread the question.
2

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));
    }

}

Comments

1

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

Comments