tags:

views:

87

answers:

2

Just curious about how jaxb works, I have a class annotated as follows:

@XmlRootElement(name = "MyJaxb")
Class MyJaxb
{
      @XmlElement
      protected String str;

      public void setStr(String str)
      {
           this.str = str;
      }
 }

The access modifier of field str is protected, why Jaxb can still marshall and unmarshall it?

+6  A: 

It uses reflection. A protected or private field or method can be accessed using the reflection API (using setAccessible(true) on the appropriate Field or Method object).

Remember - public, protected and private are controls on default visibility, nothing more. They do not (and cannot) prevent access using reflection.

skaffman
Thanks, but just curious why Java provides the interface like reflection to change the modifiers(setAccessible(true)), what is the point? I mean it breaks the idea of access control
Guoqin
@Guoqin if you really want, you can force your way through access control using reflection, but then you know that you're deliberately breaking it. Access control keywords are meant to express the intent of the programmer, they are not meant as a security tool. If a programmer makes a field `private`, (s)he's saying "you're not supposed to mess with this field yourself" - if you force it, the behaviour of the program cannot be guaranteed.
Jesper
@Jesper is right, however the ability to modify private/protected fields can be block at the level of Java security manager (if someone is paranoid enough to do it)
Piotr Kochański
A: 

Beyond answer that reflection can by-pass checks (which is correct), this is also something that other JDK internal parts need, specifically default Object serialization and deserialization. In general this is allowed because many tools benefit from such access. And like others have correctly pointed out, access rights are not meant as real security barriers. They are there to help programmers design abstractions properly, make it easier to come up with good designs.

StaxMan