Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of String variable via reflection

I have a POJO with loads of Strings and I want an easy method to check if they are all empty / contain a certain character / whatever.

I get the String variables with this:

    Field[] fields = this.getClass().getDeclaredFields();

    for (Field f : fields) {

        if (f.getType() == java.lang.String.class) {
            Log.d("REF", "Field: " + f.getName());
        }

    }

but I don't know how to get the String value of the Field. How is it done?

like image 208
fweigl Avatar asked Jun 28 '13 08:06

fweigl


People also ask

How do you find the value of field through reflection?

reflect. Field used to get the value of the field object. If Field has a primitive type then the value of the field is automatically wrapped in an object. If the field is a static field, the argument of obj is ignored; it may be null Otherwise, the underlying field is an instance field.

What is getField in Java?

getField(String name) Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object. Field[] getFields() Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.

How do you find the value of field?

The GetFieldValue method retrieves the current value of a field. The method returns the value of the field represented by FieldObject into the variable you specify. The value of variable can be a data type that can be nullable or an instance of a user class.

How do you set up a private field in a reflection?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.


1 Answers

You need to call:

Object val = f.get(this); 

OR to get String object:

String strval = (String) f.get(this); 

to get field represented by f's value.

See: Field#Get(Object)

Also: Getting and Setting Field Values

like image 63
anubhava Avatar answered Oct 08 '22 00:10

anubhava