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> 區塊中,您可以指定程式碼的來源和目標版本,並且還有一個 可以指定的 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.