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

前端 未结 5 1305
无人及你
无人及你 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:28

    Assuming a simple case, where your field is public:

    List list; // from your method
    for(Object x : list) {
        Class clazz = x.getClass();
        Field field = clazz.getField("fieldName"); //Note, this can throw an exception if the field doesn't exist.
        Object fieldValue = field.get(x);
    }
    

    But this is pretty ugly, and I left out all of the try-catches, and makes a number of assumptions (public field, reflection available, nice security manager).

    If you can change your method to return a List, this becomes very easy because the iterator then can give you type information:

    List list; //From your method
    for(Foo foo:list) {
        Object fieldValue = foo.fieldName;
    }
    

    Or if you're consuming a Java 1.4 interface where generics aren't available, but you know the type of the objects that should be in the list...

    List list;
    for(Object x: list) {
       if( x instanceof Foo) {
          Object fieldValue = ((Foo)x).fieldName;
       }
    }
    

    No reflection needed :)

提交回复
热议问题