Java Reflection to set attributes

后端 未结 3 733
遇见更好的自我
遇见更好的自我 2020-12-21 08:19

I have a class that has many settable/gettable attributes. I\'d like to use reflection to set these attributes, but I have 2 questions about my implementati

3条回答
  •  无人及你
    2020-12-21 09:01

    I think I may be overthinking this problem (i.e., I shouldn't be using reflection to set variables in this way)

    Yep. Reflection is fairly slow and should only be used as a last resort. If this is simply to avoid having so much redundant code, consider using automatic code generation. For pure data objects, I would strongly recommend using protocol buffers; it will generate the getters / setters (you only need to declare the fields). Plus it allows for easy communication of the data between C++, Java, and Python.

    If you have a class that has a lot of fields but isn't a pure data object... well

    1. You should consider whether all the fields should be mutable. (Do you really need setters?)
    2. Whether the fields should even be visible. (Do you need any accessors at all?)

    It is often a good idea to make fields "final", initialize them in the constructor(s), and provide no access or provide limited access through an implemented interface.

提交回复
热议问题