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?

Was it helpful?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top