Java reflection: how to get field value from an object, not knowing its class

前端 未结 5 1296
无人及你
无人及你 2020-11-29 04:10

Say, I have a method that returns a custom List with some objects. They are returned as Object to me. I need to get value of a certain field from t

5条回答
  •  醉梦人生
    2020-11-29 04:29

    I strongly recommend using Java generics to specify what type of object is in that List, ie. List. If you have Cars and Trucks you can use a common superclass/interface like this List.

    However, you can use Spring's ReflectionUtils to make fields accessible, even if they are private like the below runnable example:

    List list = new ArrayList();
    
    list.add("some value");
    list.add(3);
    
    for(Object obj : list)
    {
        Class clazz = obj.getClass();
    
        Field field = org.springframework.util.ReflectionUtils.findField(clazz, "value");
        org.springframework.util.ReflectionUtils.makeAccessible(field);
    
        System.out.println("value=" + field.get(obj));
    }
    
    
    

    Running this has an output of:

    value=[C@1b67f74
    value=3

    提交回复
    热议问题