Java Reflection to set attributes

后端 未结 3 725
遇见更好的自我
遇见更好的自我 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 08:38

    Using setter methods is the accepted way to set values for class member variables, reflection should definitely not be used for that as the code will be harder to understand and run much more slowly.

    Most IDEs (eg Eclipse or NetBeans) include tools for automatically creating getter and setter methods for a class's fields.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-21 09:01
    1. When they are private you need to call fld.setAccessible(true);
    2. Yes, why don't you just set the fields directly and avoid reflection? It doesn't look like you're doing anything dynamic. It's just that they are private -- why? Perhaps you mean to expose getters/setters and make the fields private? If so, then you should just invoke the public setters.
    0 讨论(0)
提交回复
热议问题