How can I determine the type of a generic field in Java?

前端 未结 7 923
无人共我
无人共我 2020-11-27 13:25

I have been trying to determine the type of a field in a class. I\'ve seen all the introspection methods but haven\'t quite figured out how to do it. This is going to be use

7条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 13:58

    As dfa points out, you can get the erased type with java.lang.reflect.Field.getType. You can get the generic type with Field.getGenericType (which may have wildcards and bound generic parameters and all sorts of craziness). You can get the fields through Class.getDeclaredFields (Class.getFields will give you public fields (including those of the supertpye) - pointless). To get the base type fields, go through Class.getSuperclass. Note to check modifiers from Field.getModifiers - static fields probably will not be interesting to you.

提交回复
热议问题