Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting fields and their values in an object via reflection Java

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

like image 722
Mavrick Flash Avatar asked Jan 19 '26 19:01

Mavrick Flash


1 Answers

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

like image 50
Jekin Kalariya Avatar answered Jan 22 '26 09:01

Jekin Kalariya