views:

101

answers:

2

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?

A: 
manager.getClass().getDeclaredFields()

Will get you access to the fields. See the javadocs here

Jim Barrows
Thanks. To me that breaks encapsulation - What's the point of private members if they can be set arbitrarily? Or is this something that annotations somehow allow?
Bedwyr Humphreys
It's safe to break encapsulation if you're following the contract of breaking encapsulation. :) Providing some annotations is the same as providing, e.g., setters.
Vladimir Dyuzhev
It's something that reflection allows. It's a convenience for things that use reflection to do certain things... you don't go around writing all your code using reflection, and it would be stupid to do so, so in general encapsulation isn't broken.
ColinD
@ColinD - so its 'be careful out there' :)
Bedwyr Humphreys
+3  A: 

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.

ChssPly76