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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With