I have an Object in java and it has multiple fields i do not know their types. I am using reflection to get the fields and their values but it isn't working as it seems to be.
Object obj = gettingObjectFromSomeMethod();
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
Object value = field.get(obj);
if (value != null) {
System.out.println(field.getName() + "=" + value);
}
}
output:
serialVersionUID=8683452581122892189
DEFAULT_CAPACITY=10
EMPTY_ELEMENTDATA=[Ljava.lang.Object;@5649fd9b
DEFAULTCAPACITY_EMPTY_ELEMENTDATA=[Ljava.lang.Object;@6adede5
elementData=[Ljava.lang.Object;@2d928643
size=4
MAX_ARRAY_SIZE=2147483639
but when i print the object it gives the following output
[{long_name=Los Angeles, short_name=Los Angeles, types=[locality, political]}, {long_name=Los Angeles County, short_name=Los Angeles County, types=[administrative_area_level_2, political]}, {long_name=California, short_name=CA, types=[administrative_area_level_1, political]}, {long_name=United States, short_name=US, types=[country, political]}]
I want to get the value of these fields.. Please suggest what to do
I have just tested the code it is returning list as object response so you can do like below. however if you want specific field you can specify if condition in inner for loop with field.getName().
if(obj instanceof List){
List myList = (List) obj;// this is your object which return from gettingObjectFromSomeMethod
for (Object object : myList) {
for (Field field : object.getClass().getDeclaredFields()) {
field.setAccessible(true);
System.out.println("field_Name"+
field.getName() + "field_Value"+field.get(object));
}
}
}
If this solution not work then please print System.out.println(obj.getClass().getName()); and let me know which time it returns
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