How does container injection of annotated private class attributes work in java?
-
06-07-2019 - |
Question
I've started reading the Enterprise Java Beans 3.0 book by Bill Burke and Richard Monson-Haefel and in chapter 4 it has this code
@PersistenceContext(unitName="titan") private EntityManager manager;
The class then has methods that access this field (which is never set in the constructor and has no setter method). So how does the container set this private field with an actual instance? I'm assuming there's some reflection and/or bytecode magic going on - how is that done?
Solution
getDeclaredFields() will return a list of fields declared in the class.
Container loops through all the fields checking for appropriate annotations. Once the needed field is found, it invokes setAccessible(true) on that field in order to be able to manipulate it from the code where it normally would not have been accessible.
OTHER TIPS
manager.getClass().getDeclaredFields()
Will get you access to the fields. See the javadocs here