How do app servers inject into private fields?

前端 未结 3 1050
孤城傲影
孤城傲影 2021-02-08 04:13

I saw this question

Inject into private, package or public field or provide a setter?

about how to manually inject into annotated private fields (The way is addi

3条回答
  •  天涯浪人
    2021-02-08 04:59

    It's a simple reflection "trick". It relies on the Field.setAccessible() method to force the member to be accessible programmatically:

    Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks.

    The Reflection API is used to get a handle on the field, setAccessible() is called, and then it can be set by the injection framework.

    See an example here.

    No magic, no custom VM.

提交回复
热议问题