Insert custom annotation in java 'field' u

2019-02-12 19:06发布

问题:

Use case:

Wanna insert custom annotation to fields in java class generated by JAXB

Problem:

Using Annotate plugin + JAXB [1], am able to successfully insert custom annotations but they are getting inserted at getter method rather than field. Morphia (mongo DB) annotations (that i actually want to insert) however can annotate only java fields [2].

My test xsd:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" jaxb:version="2.1"
xmlns:annox="http://annox.dev.java.net" jaxb:extensionBindingPrefixes="annox">

<xsd:element name="hoo" type="External" />
<xsd:complexType name="External">
    <xsd:sequence>
        <xsd:element name="bar" type="xsd:string" />
        <xsd:element name="hoobar" type="xsd:string" />
    </xsd:sequence>
</xsd:complexType>
</xsd:schema>

My test binding xjb:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxb:bindings
 version="2.1"
 xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"

  xmlns:annox="http://annox.dev.java.net" jaxb:extensionBindingPrefixes="annox">
  <jaxb:bindings schemaLocation="external.xsd" node="/xs:schema">

<jaxb:bindings node="xs:complexType[@name='External']/xs:sequence/xs:element[@name='bar']">
  <annox:annotate>
    <annox:annotate
      annox:class="java.lang.SuppressWarnings"
      impl="com.acme.foo.MyFieldBridge">
    </annox:annotate>
  </annox:annotate>
</jaxb:bindings>    

My generated java snippet:

 @XmlElement(required = true)
protected String bar;
@XmlElement(required = true)
protected String hoobar;

/**
 * Gets the value of the bar property.
 * 
 * @return
 *     possible object is
 *     {@link String }
 *     
 */
@SuppressWarnings({

})
public String getBar() {
    return bar;
}

As you can see, i want to annotate "bar" field. Please advise. Ask for more if needed.

[1] Generate @Indexed annotation using Jaxb or HyperJaxb
[2] For sample see @Id annotation of Morphia

回答1:

Ok, you figured it out yourself. Use <annox:annotate target="field"> to annotate a field. Other options are:

  • setter
  • setter-parameter
  • getter
  • field
  • class

See the documentation.



回答2:

Just one more thing: you need to put the field attribute to the outer <annox:annotate> tag:

<annox:annotate target="field">
    <annox:annotate annox:class="java.lang.SuppressWarnings"/>
</annox:annotate>

Putting it to the same tag as the annox:class attribute resides might not work. That happend to me.