簡體   English   中英

修改java類以在編譯時包含特定注釋

[英]Modify java classes to include specific annotations at compile time

我有許多由JAXB的xsd2java生成的類。 我需要在編譯時使用特定注釋對所有這些類進行注釋(例如使用lombok注釋)。 有沒有辦法做到這一點,例如一些代碼生成工具?

免責聲明:我是JAXB2 Annotate Plugin的作者,它允許您向模式派生類添加任意注釋。

簡短的例子:

<xsd:complexType name="FooType">
    <xsd:annotation>
        <xsd:appinfo>
            <annox:annotate>@java.lang.SuppressWarnings({"unchecked","rawtypes"})</annox:annotate>
            <annox:annotate target="package">@javax.annotation.Generated({"XJC","JAXB2 Annotate Plugin"})</annox:annotate>
        </xsd:appinfo>
    </xsd:annotation>
    <xsd:sequence>
        <xsd:element name="bar" type="xsd:string"/>
        <xsd:element name="foobar" type="xsd:string">
            <xsd:annotation>
                <xsd:appinfo>
                    <annox:annotate>@java.lang.SuppressWarnings({"unchecked","rawtypes"})</annox:annotate>
                    <annox:annotate target="setter">@java.lang.Deprecated</annox:annotate>
                    <annox:annotate target="setter-parameter">@java.lang.Deprecated</annox:annotate>
                    <annox:annotate target="getter">@java.lang.Deprecated</annox:annotate>
                    <annox:annotate target="field">@java.lang.Deprecated</annox:annotate>
                    <annox:annotate target="class">@java.lang.Deprecated</annox:annotate>
                </xsd:appinfo>
            </xsd:annotation>
        </xsd:element>
    </xsd:sequence>
</xsd:complexType>

也適用於外部綁定文件。

限制:

  • 注釋以Java語法提供,但您必須使用完全限定名稱。
  • 您必須在XJC類路徑中包含注釋類(例如lombok),因為這些類在模式編譯期間必須可用。

PS。 我假設當你說xsd2java你可能意味着XJC

更新

OP在評論中詢問如何使用配置它。

您也可以將jaxb2-annotate-plugin 我從來沒有嘗試過。

  • 您可以使用pom.xmldependencies/depenency將其他JAR包含到類路徑中。
  • 然后,您需要在配置中添加arguments

有關示例,請參閱此答案(和問題):

https://stackoverflow.com/a/12804497/303810

它是關於其他插件,但你會得到一個如何使用Codehaus 配置它的線索。

使用我的進行配置如下:

<plugin>
    <groupId>org.jvnet.jaxb2.maven2</groupId>
    <artifactId>maven-jaxb2-plugin</artifactId>
    <configuration>
        <extension>true</extension>
        <args>
            <arg>-Xannotate</arg>
        </args>
        <plugins>
            <plugin>
                <groupId>org.jvnet.jaxb2_commons</groupId>
                <artifactId>jaxb2-basics-annotate</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jvnet.jaxb2_commons</groupId>
                <artifactId>jaxb2-annotate-plugin-test-annox-annotations</artifactId>
            </plugin>
        </plugins>
    </configuration>
</plugin>

這部分:

<plugin>
    <groupId>org.jvnet.jaxb2_commons</groupId>
    <artifactId>jaxb2-annotate-plugin-test-annox-annotations</artifactId>
</plugin>

指的是包含注釋類的工件。

這是 / 組合的示例pom.xml

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM