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

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

    If you know what class the field is on you can access it using reflection. This example (it's in Groovy but the method calls are identical) gets a Field object for the class Foo and gets its value for the object b. It shows that you don't have to care about the exact concrete class of the object, what matters is that you know the class the field is on and that that class is either the concrete class or a superclass of the object.

    groovy:000> class Foo { def stuff = "asdf"}
    ===> true
    groovy:000> class Bar extends Foo {}
    ===> true
    groovy:000> b = new Bar()
    ===> Bar@1f2be27
    groovy:000> f = Foo.class.getDeclaredField('stuff')
    ===> private java.lang.Object Foo.stuff
    groovy:000> f.getClass()
    ===> class java.lang.reflect.Field
    groovy:000> f.setAccessible(true)
    ===> null
    groovy:000> f.get(b)
    ===> asdf
    

提交回复
热议问题