为何Maven项目中List的getLast()方法无法正常工作?
Maven构建Java21代码时找不到List.getLast()方法的解决办法
问题场景
以下代码直接运行正常,但在Maven项目构建阶段报错:
import java.util.List; public class Test { public static void main(String[] args){ List<Integer> a = List.of(1, 2, 3); a.getLast(); } }
报错信息:
java: cannot find symbol symbol: method getLast() location: variable a of type java.util.List<java.lang.Integer>
点击getLast()能在List类中找到该默认方法:
default E getLast() { if (this.isEmpty()) { throw new NoSuchElementException(); } else { return this.get(this.size() - 1); } }
使用环境:
- Apache Maven 3.8.8
- Java version: 21
- Windows 11 (10.0)
原因分析
List.getLast()是Java 21新增的默认方法,Maven默认可能使用了低于21的Java版本进行编译——即使本地安装的是JDK21,只要compiler插件没指定正确版本,编译时就会调用老版本的JDK API,自然找不到这个新增方法。
解决办法
在项目的pom.xml中配置maven-compiler-plugin,明确指定编译用的Java版本为21:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>21</source> <target>21</target> <release>21</release> </configuration> </plugin> </plugins> </build>
配置完成后重新执行mvn clean install,构建就能正常通过了。
内容的提问来源于stack exchange,提问作者Alexey
相关产品推荐
相关产品推荐

