Add compiler argument to build Maven project

English 简体中文 繁体中文 ภาษาไทย Tiếng Việt
Summary

Maven projects often require passing specific arguments to the Java compiler, such as defining source and target releases or handling options like -XDignore.symbol.file for Java 8's modularized source code. To integrate these arguments into a Maven build, developers must configure the maven-compiler-plugin within their project's pom.xml. For plugin versions 3.1 and later, compiler arguments are specified using the block containing multiple elements. Earlier versions (prior to 3.1) utilize a single tag, which has the limitation of only processing the last argument if multiple are provided. Therefore, it is strongly recommended to use maven-compiler-plugin version 3.1 or newer for reliable and flexible compiler argument management.

Maven 是一个软件项目,用于从一个中心信息管理项目的构建、报告和文档。它现在被广泛用于构建和部署项目。它可以帮助自动维护项目的依赖关系。有一个名为 pom.xml 的中心项目配置文件。在这里,您可以配置要构建的项目。

在这篇文章中,我们将向您展示在使用 javac 编译 Java 源代码时如何添加编译器参数。有时,当编译源代码时,我们需要传递编译器参数,例如,我们可能需要指定代码的 -source 和 -target 版本。特别是在最新的 Java 8 中,源代码现在是模块化的,当 javac 编译代码时,默认情况下它不会链接到最新的 Java 8 中的 rt.jar。相反,它使用带有类存根的特殊符号文件 lib/ct.sym。选项 -XDignore.symbol.file 是为了忽略符号文件,以便它将链接到 rt.jar。

要添加编译器参数,您需要将编译器插件添加到项目的 pom.xml 文件中。这是一个示例插件配置:

<build>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>3.3</version>
			<configuration>
				<source>1.8</source> 
				<target>1.8</target> 
				<fork>true</fork>
				<compilerArgs>
					<arg>-XDignore.symbol.file</arg>
				</compilerArgs>
			</configuration>
		</plugin>
	</plugins>
</build>

在此配置中,插件版本在这里非常重要。在 maven-compiler-plugin 3.1 之前,编译器参数应该是 <compilerArgument>-XDignore.symbol.file</compilerArgument>,并且它有一个限制,如果您放置多个 <compilerArgument>...</compilerArgument>,则只会选择最后一个,而所有其他参数都将被忽略。

<build>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>3.0</version>
			<configuration>
				<source>1.8</source> 
				<target>1.8</target> 
				<fork>true</fork>
				<compilerArgument>-XDignore.symbol.file</compilerArgument>
			</configuration>
		</plugin>
	</plugins>
</build>

因此,我们强烈建议您使用 3.1 或更高版本的插件。在 <configuration> 块中,您可以指定代码的 source 和 target 版本,并且还可以指定 javac 选项列表

您可以使用命令行选项 -X 运行 maven 以显示调试信息,在那里您将看到您指定的编译器参数。例如:

MAVEN COMPILER ARGUMENT COMPILER OPTION JAVA 8

  RELATED

  COMMENT

1
Rohit
Apr 12, 2015 at 11:01 pm

Good tutorial Keep it up.