專案編譯執行時拋出 Unsupported major.minor version 51.0 錯誤,導致類別無法載入。
Major.minor version 51.0 對應 JDK 7 編譯的類別檔案。 當使用 JDK 7 編譯的 .class 檔案部署到運行於 JDK 6 (或更舊版本) 的 Tomcat 容器中時,執行環境無法識別較新版本的類別檔案格式,因而拋出此錯誤。
| JDK 版本 | Major Version (十進位) | Major Version (十六進位) |
|---|---|---|
| JDK 1.4 | 48 | 0x30 |
| JDK 5 | 49 | 0x31 |
| JDK 6 | 50 | 0x32 |
| JDK 7 | 51 | 0x33 |
| JDK 8 | 52 | 0x34 |
| JDK 11 | 55 | 0x37 |
| JDK 17 | 61 | 0x3D |
確保開發機、建置伺服器、生產環境 Tomcat 使用相同的 JDK 版本,從根源避免版本不匹配。
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<!-- 或在 plugin 設定 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
major.minor version 位於 .class 檔案標頭,代表類別檔案格式版本。JVM 載入類別時會檢查此版本號,若高於 JVM 支援的最高版本,即拋出 UnsupportedClassVersionError。
版本不相容是 Java 開發常見問題,核心原則是:編譯目標版本不得高於運行環境版本。建議專案初期即規範 JDK 版本,並在 CI/CD 流程中強制檢查。