6

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?

3 Answers 3

5

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

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

Comments

2

You can try this code to get the value :

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

Comments

2

For any object you should use Field#get(Object) method. as String is an object in java thus :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.