繁体   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