how java jaxb works?

2019-02-22 07:37发布

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?

标签: java jaxb
2条回答
太酷不给撩
2楼-- · 2019-02-22 08:15

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.

查看更多
叛逆
3楼-- · 2019-02-22 08:17

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.

查看更多
登录 后发表回答