@echo off
REM switch_jdk.bat - JDK 版本切换脚本
REM 💡 重点提示:这是最基础的 JDK 切换脚本,适合快速上手
echo === JDK Version Switcher ===
echo.
echo Available JDK versions:
echo 1. JDK 8
echo 2. JDK 11
echo 3. JDK 17
echo 4. JDK 21
echo 5. Show current version
echo 0. Exit
echo.
set /p choice="Please select JDK version (0-5): "
if "%choice%"=="1" goto JDK8
if "%choice%"=="2" goto JDK11
if "%choice%"=="3" goto JDK17
if "%choice%"=="4" goto JDK21
if "%choice%"=="5" goto SHOW
if "%choice%"=="0" goto EXIT
goto INVALID
:JDK8
set JAVA_HOME=C:\Java\jdk-8
echo Switched to JDK 8
goto VERIFY
:JDK11
set JAVA_HOME=C:\Java\jdk-11
echo Switched to JDK 11
goto VERIFY
:JDK17
set JAVA_HOME=C:\Java\jdk-17
echo Switched to JDK 17
goto VERIFY
:JDK21
set JAVA_HOME=C:\Java\jdk-21
echo Switched to JDK 21
goto VERIFY
:SHOW
echo Current JAVA_HOME: %JAVA_HOME%
"%JAVA_HOME%\bin\java" -version
goto END
:VERIFY
echo.
echo New JAVA_HOME: %JAVA_HOME%
echo Verifying installation...
"%JAVA_HOME%\bin\java" -version
goto END
:INVALID
echo Invalid choice! Please try again.
goto END
:EXIT
echo Goodbye!
exit /b 0
:END
echo.
pause
4.2 高级批处理脚本
创建一个功能更完善的切换脚本:
@echo off
REM advanced_jdk_switch.bat - 高级 JDK 切换脚本
REM 🚀 实用技巧:这个脚本包含日志记录、历史查看、永久设置等高级功能
setlocal enabledelayedexpansion
REM 配置 JDK 安装路径
set JDK_BASE_PATH=C:\Java
set JDK8_PATH=%JDK_BASE_PATH%\jdk-8
set JDK11_PATH=%JDK_BASE_PATH%\jdk-11
set JDK17_PATH=%JDK_BASE_PATH%\jdk-17
set JDK21_PATH=%JDK_BASE_PATH%\jdk-21
REM 日志文件
set LOG_FILE=%~dp0jdk_switch.log
:MAIN
cls
echo ╔══════════════════════════════════════╗
echo ║ JDK Version Manager ║
echo ╚══════════════════════════════════════╝
echo.
REM 检查当前 JDK 版本
call :CHECK_CURRENT
echo Available operations:
echo [1] Switch to JDK 8
echo [2] Switch to JDK 11
echo [3] Switch to JDK 17
echo [4] Switch to JDK 21
echo [5] List all installed JDKs
echo [6] Verify current installation
echo [7] Set JAVA_HOME permanently
echo [8] View switch history
echo [0] Exit
echo.
set /p "choice=Select option (0-8): "
if "%choice%"=="1" call :SWITCH_JDK "8" "%JDK8_PATH%"
if "%choice%"=="2" call :SWITCH_JDK "11" "%JDK11_PATH%"
if "%choice%"=="3" call :SWITCH_JDK "17" "%JDK17_PATH%"
if "%choice%"=="4" call :SWITCH_JDK "21" "%JDK21_PATH%"
if "%choice%"=="5" call :LIST_JDKS
if "%choice%"=="6" call :VERIFY_INSTALLATION
if "%choice%"=="7" call :SET_PERMANENT
if "%choice%"=="8" call :SHOW_HISTORY
if "%choice%"=="0" goto :EXIT
echo.
pause
goto :MAIN
REM 检查当前 JDK 版本
:CHECK_CURRENT
echo Current Status:
if defined JAVA_HOME (
echo JAVA_HOME: %JAVA_HOME%
if exist "%JAVA_HOME%\bin\java.exe" (
for /f "tokens=3" %%a in ('"%JAVA_HOME%\bin\java" -version 2^>^&1 ^| findstr "version"') do (
set CURRENT_VERSION=%%a
set CURRENT_VERSION=!CURRENT_VERSION:"=!
)
echo Current Version: !CURRENT_VERSION!
) else (
echo ❌ JAVA_HOME points to invalid path
)
) else (
echo ❌ JAVA_HOME not set
)
echo ----------------------------------------
return
REM 切换 JDK 版本
:SWITCH_JDK
set JDK_VERSION=%~1
set JDK_PATH=%~2
echo.
echo Switching to JDK %JDK_VERSION%...
REM 检查 JDK 是否存在
if not exist "%JDK_PATH%\bin\java.exe" (
echo ❌ JDK %JDK_VERSION% not found at: %JDK_PATH%
echo Please install JDK %JDK_VERSION% first.
return
)
REM 设置环境变量
set JAVA_HOME=%JDK_PATH%
set PATH=%JAVA_HOME%\bin;%PATH%
REM 验证切换结果
echo ✅ Successfully switched to JDK %JDK_VERSION%
echo New JAVA_HOME: %JAVA_HOME%
echo.
REM 显示版本信息
"%JAVA_HOME%\bin\java" -version
REM 记录切换历史
echo [%date% %time%] Switched to JDK %JDK_VERSION% at %JDK_PATH% >> "%LOG_FILE%"
return
REM 列出所有已安装的 JDK
:LIST_JDKS
echo.
echo ═══ Installed JDK Versions ═══
set JDK_FOUND=0
if exist "%JDK8_PATH%\bin\java.exe" (
echo ✅ JDK 8 - %JDK8_PATH%
set /a JDK_FOUND+=1
)
if exist "%JDK11_PATH%\bin\java.exe" (
echo ✅ JDK 11 - %JDK11_PATH%
set /a JDK_FOUND+=1
)
if exist "%JDK17_PATH%\bin\java.exe" (
echo ✅ JDK 17 - %JDK17_PATH%
set /a JDK_FOUND+=1
)
if exist "%JDK21_PATH%\bin\java.exe" (
echo ✅ JDK 21 - %JDK21_PATH%
set /a JDK_FOUND+=1
)
if %JDK_FOUND%==0 (
echo ❌ No JDK installations found
echo Please install JDK versions in: %JDK_BASE_PATH%
)
echo.
echo Total JDK versions found: %JDK_FOUND%
return
REM 验证当前安装
:VERIFY_INSTALLATION
echo.
echo ═══ Installation Verification ═══
if not defined JAVA_HOME (
echo ❌ JAVA_HOME is not set
return
)
echo JAVA_HOME: %JAVA_HOME%
if not exist "%JAVA_HOME%\bin\java.exe" (
echo ❌ java.exe not found
return
)
if not exist "%JAVA_HOME%\bin\javac.exe" (
echo ❌ javac.exe not found
return
)
echo ✅ Java Runtime: "%JAVA_HOME%\bin\java" -version
echo.
echo ✅ Java Compiler: "%JAVA_HOME%\bin\javac" -version
echo.
echo ✅ Installation verification passed!
return
REM 永久设置 JAVA_HOME
:SET_PERMANENT
echo.
echo ═══ Set JAVA_HOME Permanently ═══
echo.
echo This will set JAVA_HOME in system environment variables.
echo Current session JAVA_HOME: %JAVA_HOME%
echo.
set /p "confirm=Make this permanent? (y/n): "
if /i "%confirm%"=="y" (
echo Setting JAVA_HOME permanently...
setx JAVA_HOME "%JAVA_HOME%" /M >nul 2>&1
if errorlevel 1 (
echo ❌ Failed to set system variable. Try running as Administrator.
setx JAVA_HOME "%JAVA_HOME%" >nul 2>&1
if errorlevel 1 (
echo ❌ Failed to set user variable as well.
) else (
echo ✅ Set JAVA_HOME for current user only.
)
) else (
echo ✅ JAVA_HOME set permanently for all users.
)
) else (
echo Operation cancelled.
)
return
REM 显示切换历史
:SHOW_HISTORY
echo.
echo ═══ JDK Switch History ═══
if exist "%LOG_FILE%" (
type "%LOG_FILE%"
) else (
echo No switch history found.
)
return
:EXIT
echo.
echo Thanks for using JDK Version Manager!
exit /b 0
4.3 创建桌面快捷方式
REM create_shortcut.bat - 创建桌面快捷方式
@echo off
set SCRIPT_PATH=%~dp0advanced_jdk_switch.bat
set SHORTCUT_PATH=%USERPROFILE%\Desktop\JDK Switcher.lnk
REM 使用 PowerShell 创建快捷方式
powershell -Command "& {$WshShell = New-Object -comObject WScript.Shell; $Shortcut = $WshShell.CreateShortcut('%SHORTCUT_PATH%'); $Shortcut.TargetPath = '%SCRIPT_PATH%'; $Shortcut.WorkingDirectory = '%~dp0'; $Shortcut.IconLocation = 'C:\Windows\System32\cmd.exe,0'; $Shortcut.Description = 'JDK Version Switcher'; $Shortcut.Save()}"
echo Desktop shortcut created: %SHORTCUT_PATH%
pause
4.4 项目级 JDK 配置
创建项目专用的 JDK 配置脚本:
REM project_jdk.bat - 项目级 JDK 配置
REM 💡 重点提示:将此脚本放在项目根目录,配合.jdkversion 文件使用
@echo off
REM 检查项目配置文件
if exist ".jdkversion" (
set /p PROJECT_JDK=<.jdkversion
echo Found project JDK configuration: %PROJECT_JDK%
REM 根据配置设置 JDK
if "%PROJECT_JDK%"=="8" set JAVA_HOME=C:\Java\jdk-8
if "%PROJECT_JDK%"=="11" set JAVA_HOME=C:\Java\jdk-11
if "%PROJECT_JDK%"=="17" set JAVA_HOME=C:\Java\jdk-17
if "%PROJECT_JDK%"=="21" set JAVA_HOME=C:\Java\jdk-21
set PATH=%JAVA_HOME%\bin;%PATH%
echo Project JDK set to: %JAVA_HOME%
java -version
) else (
echo No .jdkversion file found in current directory
echo Create .jdkversion file with content: 8, 11, 17, or 21
)
REM 启动项目开发环境
if exist "pom.xml" (
echo Maven project detected
mvn --version
) else if exist "build.gradle" (
echo Gradle project detected
gradle --version
) else if exist "build.sbt" (
echo SBT project detected
sbt about
)
cmd /k
在项目根目录创建 .jdkversion 文件:
17
这样每次进入项目目录运行 project_jdk.bat 就会自动切换到项目所需的 JDK 版本。
5. 方案三:PowerShell 高级脚本
🎯 适用人群: 熟悉 PowerShell 的高级用户、系统管理员、需要复杂自动化的开发者
📋 适用场景: 企业环境、复杂的 JDK 管理需求、需要详细日志和配置管理的场景
5.1 PowerShell JDK 管理器
创建一个功能强大的 PowerShell JDK 管理脚本:
# JDKManager.ps1 - PowerShell JDK 版本管理器
# 🔧 重点提示:这是功能最完整的 JDK 管理器,支持命令行参数和交互式菜单
param([string]$Action = "menu",[string]$Version = "",[switch]$List,[switch]$Current,[switch]$Install,[switch]$Remove,[switch]$Permanent,[switch]$Help)
# 配置参数
$JDK_BASE_PATH = "C:\Java"
$CONFIG_FILE = "$env:USERPROFILE\.jdkmanager.json"
$LOG_FILE = "$env:USERPROFILE\.jdkmanager.log"
# JDK 版本配置
$JDK_VERSIONS = @{
"8" = @{"Path" = "$JDK_BASE_PATH\jdk-8"; "Name" = "Oracle JDK 8"; "LTS" = $true}
"11" = @{"Path" = "$JDK_BASE_PATH\jdk-11"; "Name" = "Oracle JDK 11"; "LTS" = $true}
"17" = @{"Path" = "$JDK_BASE_PATH\jdk-17"; "Name" = "Oracle JDK 17"; "LTS" = $true}
"21" = @{"Path" = "$JDK_BASE_PATH\jdk-21"; "Name" = "Oracle JDK 21"; "LTS" = $true}
}
# 日志函数
function Write-Log {
param([string]$Message,[string]$Level = "INFO")
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "[$timestamp] [$Level] $Message"
Add-Content -Path $LOG_FILE -Value $logEntry
switch($Level) {
"ERROR" { Write-Host $logEntry -ForegroundColor Red }
"WARN" { Write-Host $logEntry -ForegroundColor Yellow }
"SUCCESS" { Write-Host $logEntry -ForegroundColor Green }
default { Write-Host $logEntry -ForegroundColor White }
}
}
# 检查 JDK 是否已安装
function Test-JDKInstallation {
param([string]$JDKPath)
return (Test-Path "$JDKPath\bin\java.exe") -and (Test-Path "$JDKPath\bin\javac.exe")
}
# 获取 JDK 版本信息
function Get-JDKVersion {
param([string]$JDKPath)
if (Test-JDKInstallation -JDKPath $JDKPath) {
try {
$versionOutput = & "$JDKPath\bin\java.exe" -version 2>&1
$versionLine = $versionOutput | Select-String "version" | Select-Object -First 1
return $versionLine.ToString()
} catch {
return "Unknown version"
}
}
return "Not installed"
}
# 列出所有 JDK 版本
function Show-JDKList {
Write-Host "`n═══ Installed JDK Versions ═══" -ForegroundColor Cyan
$installedCount = 0
foreach ($version in $JDK_VERSIONS.Keys | Sort-Object) {
$jdkInfo = $JDK_VERSIONS[$version]
$isInstalled = Test-JDKInstallation -JDKPath $jdkInfo.Path
if ($isInstalled) {
$versionInfo = Get-JDKVersion -JDKPath $jdkInfo.Path
$ltsTag = if ($jdkInfo.LTS) {" (LTS)"} else {""}
Write-Host "✅ JDK $version$ltsTag - $($jdkInfo.Path)" -ForegroundColor Green
Write-Host " $versionInfo" -ForegroundColor Gray
$installedCount++
} else {
Write-Host "❌ JDK $version - Not installed" -ForegroundColor Red
}
}
Write-Host "`nTotal installed: $installedCount" -ForegroundColor Yellow
}
# 显示当前 JDK 状态
function Show-CurrentJDK {
Write-Host "`n═══ Current JDK Status ═══" -ForegroundColor Cyan
if ($env:JAVA_HOME) {
Write-Host "JAVA_HOME: $env:JAVA_HOME" -ForegroundColor Green
if (Test-JDKInstallation -JDKPath $env:JAVA_HOME) {
$versionInfo = Get-JDKVersion -JDKPath $env:JAVA_HOME
Write-Host "Version: $versionInfo" -ForegroundColor Green
} else {
Write-Host "❌ JAVA_HOME points to invalid JDK installation" -ForegroundColor Red
}
} else {
Write-Host "❌ JAVA_HOME is not set" -ForegroundColor Red
}
# 检查 PATH 中的 Java
$javaInPath = Get-Command java -ErrorAction SilentlyContinue
if ($javaInPath) {
Write-Host "Java in PATH: $($javaInPath.Source)" -ForegroundColor Green
} else {
Write-Host "❌ Java not found in PATH" -ForegroundColor Red
}
}
# 切换 JDK 版本
function Switch-JDK {
param([string]$TargetVersion)
if (-not $JDK_VERSIONS.ContainsKey($TargetVersion)) {
Write-Log "Invalid JDK version: $TargetVersion" "ERROR"
Write-Host "Available versions: $($JDK_VERSIONS.Keys -join', ')" -ForegroundColor Yellow
return $false
}
$jdkInfo = $JDK_VERSIONS[$TargetVersion]
if (-not (Test-JDKInstallation -JDKPath $jdkInfo.Path)) {
Write-Log "JDK $TargetVersion is not installed at $($jdkInfo.Path)" "ERROR"
return $false
}
# 设置环境变量
$env:JAVA_HOME = $jdkInfo.Path
$env:PATH = "$( $jdkInfo.Path )\bin;" + ($env:PATH -replace [regex]::Escape("$( $jdkInfo.Path )\bin;"), "")
Write-Log "Switched to JDK $TargetVersion at $($jdkInfo.Path)" "SUCCESS"
# 显示版本信息
& "$( $jdkInfo.Path )\bin\java.exe" -version
# 保存当前配置
Save-Configuration -CurrentVersion $TargetVersion
return $true
}
# 永久设置 JAVA_HOME
function Set-PermanentJavaHome {
param([string]$JDKPath)
try {
# 尝试设置系统环境变量
[Environment]::SetEnvironmentVariable("JAVA_HOME", $JDKPath, "Machine")
Write-Log "JAVA_HOME set permanently for all users" "SUCCESS"
return $true
} catch {
try {
# 设置用户环境变量
[Environment]::SetEnvironmentVariable("JAVA_HOME", $JDKPath, "User")
Write-Log "JAVA_HOME set permanently for current user" "SUCCESS"
return $true
} catch {
Write-Log "Failed to set JAVA_HOME permanently: $($_.Exception.Message)" "ERROR"
return $false
}
}
}
# 保存配置
function Save-Configuration {
param([string]$CurrentVersion)
$config = @{"LastUsed" = $CurrentVersion; "LastUpdate" = Get-Date -Format "yyyy-MM-dd HH:mm:ss"; "JDKBasePath" = $JDK_BASE_PATH}
$config | ConvertTo-Json | Set-Content -Path $CONFIG_FILE
}
# 加载配置
function Load-Configuration {
if (Test-Path $CONFIG_FILE) {
try {
return Get-Content -Path $CONFIG_FILE | ConvertFrom-Json
} catch {
Write-Log "Failed to load configuration: $($_.Exception.Message)" "WARN"
}
}
return $null
}
# 自动检测已安装的 JDK
function Find-InstalledJDKs {
Write-Host "`n🔍 Scanning for JDK installations..." -ForegroundColor Cyan
$commonPaths = @("C:\Program Files\Java", "C:\Program Files (x86)\Java", "C:\Java", "C:\jdk*", "$env:USERPROFILE\Java")
$foundJDKs = @()
foreach ($basePath in $commonPaths) {
if (Test-Path $basePath) {
$jdkDirs = Get-ChildItem -Path $basePath -Directory | Where-Object { $_.Name -match "jdk" }
foreach ($dir in $jdkDirs) {
if (Test-JDKInstallation -JDKPath $dir.FullName) {
$version = Get-JDKVersion -JDKPath $dir.FullName
$foundJDKs += @{"Path" = $dir.FullName; "Version" = $version; "Name" = $dir.Name}
}
}
}
}
if ($foundJDKs.Count -gt 0) {
Write-Host "`n✅ Found $($foundJDKs.Count) JDK installation(s):" -ForegroundColor Green
foreach ($jdk in $foundJDKs) {
Write-Host " $($jdk.Name) - $($jdk.Path)" -ForegroundColor White
Write-Host " $($jdk.Version)" -ForegroundColor Gray
}
} else {
Write-Host "`n❌ No JDK installations found" -ForegroundColor Red
}
return $foundJDKs
}
# 显示帮助信息
function Show-Help {
Write-Host @"
JDK Manager for Windows - PowerShell Edition
USAGE: .\JDKManager.ps1 [OPTIONS]
OPTIONS:
-Action <action> Action to perform (menu, switch, list, current, scan)
-Version <version> JDK version to switch to (8, 11, 17, 21)
-List List all configured JDK versions
-Current Show current JDK status
-Install Install JDK (interactive)
-Remove Remove JDK configuration
-Permanent Set JAVA_HOME permanently
-Help Show this help message
EXAMPLES:
.\JDKManager.ps1 # Show interactive menu
.\JDKManager.ps1 -Action switch -Version 17 # Switch to JDK 17
.\JDKManager.ps1 -List # List all JDK versions
.\JDKManager.ps1 -Current # Show current JDK
.\JDKManager.ps1 -Action scan # Scan for JDK installations
CONFIGURATION:
Config file: $CONFIG_FILE
Log file: $LOG_FILE
JDK base path: $JDK_BASE_PATH
"@ -ForegroundColor Green
}
# 交互式菜单
function Show-InteractiveMenu {
do {
Clear-Host
Write-Host "╔══════════════════════════════════════╗" -ForegroundColor Cyan
Write-Host "║ JDK Version Manager ║" -ForegroundColor Cyan
Write-Host "║ PowerShell Edition ║" -ForegroundColor Cyan
Write-Host "╚══════════════════════════════════════╝" -ForegroundColor Cyan
Write-Host ""
# 显示当前状态
Show-CurrentJDK
Write-Host "`n📋 Available Actions:" -ForegroundColor Yellow
Write-Host "[1] Switch JDK Version" -ForegroundColor White
Write-Host "[2] List All JDK Versions" -ForegroundColor White
Write-Host "[3] Scan for JDK Installations" -ForegroundColor White
Write-Host "[4] Set JAVA_HOME Permanently" -ForegroundColor White
Write-Host "[5] View Switch History" -ForegroundColor White
Write-Host "[6] Configuration Management" -ForegroundColor White
Write-Host "[7] Help" -ForegroundColor White
Write-Host "[0] Exit" -ForegroundColor Red
Write-Host ""
$choice = Read-Host "Select option (0-7)"
switch ($choice) {
"1" {
Write-Host "`nAvailable JDK versions:" -ForegroundColor Yellow
foreach ($version in $JDK_VERSIONS.Keys | Sort-Object) {
$isInstalled = Test-JDKInstallation -JDKPath $JDK_VERSIONS[$version].Path
$status = if ($isInstalled) {"✅"} else {"❌"}
Write-Host "$status JDK $version" -ForegroundColor White
}
$targetVersion = Read-Host "`nEnter JDK version to switch to"
if ($targetVersion) {
Switch-JDK -TargetVersion $targetVersion
Read-Host "`nPress Enter to continue"
}
}
"2" {
Show-JDKList
Read-Host "`nPress Enter to continue"
}
"3" {
Find-InstalledJDKs
Read-Host "`nPress Enter to continue"
}
"4" {
if ($env:JAVA_HOME) {
Write-Host "`nCurrent JAVA_HOME: $env:JAVA_HOME" -ForegroundColor Green
$confirm = Read-Host "Set this as permanent JAVA_HOME? (y/n)"
if ($confirm -eq "y" -or $confirm -eq "Y") {
Set-PermanentJavaHome -JDKPath $env:JAVA_HOME
}
} else {
Write-Host "`n❌ JAVA_HOME is not set. Please switch to a JDK version first." -ForegroundColor Red
}
Read-Host "`nPress Enter to continue"
}
"5" {
if (Test-Path $LOG_FILE) {
Write-Host "`n═══ Switch History ═══" -ForegroundColor Cyan
Get-Content $LOG_FILE | Select-Object -Last 20
} else {
Write-Host "`n❌ No history found" -ForegroundColor Red
}
Read-Host "`nPress Enter to continue"
}
"6" {
Write-Host "`n═══ Configuration ═══" -ForegroundColor Cyan
Write-Host "Config file: $CONFIG_FILE" -ForegroundColor White
Write-Host "Log file: $LOG_FILE" -ForegroundColor White
Write-Host "JDK base path: $JDK_BASE_PATH" -ForegroundColor White
$config = Load-Configuration
if ($config) {
Write-Host "Last used: JDK $($config.LastUsed)" -ForegroundColor Green
Write-Host "Last update: $($config.LastUpdate)" -ForegroundColor Green
}
Read-Host "`nPress Enter to continue"
}
"7" {
Show-Help
Read-Host "`nPress Enter to continue"
}
"0" {
Write-Host "`n👋 Goodbye!" -ForegroundColor Green
return
}
default {
Write-Host "`n❌ Invalid option. Please try again." -ForegroundColor Red
Start-Sleep 2
}
}
} while ($true)
}
# 主执行逻辑
function Main {
# 创建必要的目录
if (-not (Test-Path $JDK_BASE_PATH)) {
New-Item -ItemType Directory -Path $JDK_BASE_PATH -Force | Out-Null
}
# 处理命令行参数
if ($Help) {
Show-Help
return
}
if ($List) {
Show-JDKList
return
}
if ($Current) {
Show-CurrentJDK
return
}
# 根据 Action 参数执行相应操作
switch ($Action.ToLower()) {
"switch" {
if ($Version) {
Switch-JDK -TargetVersion $Version
} else {
Write-Host "❌ Version parameter required for switch action" -ForegroundColor Red
Show-Help
}
}
"list" { Show-JDKList }
"current" { Show-CurrentJDK }
"scan" { Find-InstalledJDKs }
"menu" { Show-InteractiveMenu }
default { Show-InteractiveMenu }
}
}
# 执行主函数
Main
REM auto_switch.bat - 放在项目根目录
REM 🔧 重点提示:智能检测项目类型,自动切换到项目所需的 JDK 版本
@echo off
REM 检查项目类型和 JDK 要求
if exist "pom.xml" (
REM Maven 项目,检查 pom.xml 中的 Java 版本
findstr /C:"<java.version>" pom.xml > nul
if not errorlevel 1 (
for /f "tokens=2 delims=<>" %%a in ('findstr /C:"<java.version>" pom.xml') do (
set PROJECT_JAVA_VERSION=%%a
)
)
) else if exist "build.gradle" (
REM Gradle 项目,检查 build.gradle 中的 Java 版本
findstr /C:"sourceCompatibility" build.gradle > nul
if not errorlevel 1 (
for /f "tokens=3" %%a in ('findstr /C:"sourceCompatibility" build.gradle') do (
set PROJECT_JAVA_VERSION=%%a
)
)
)
REM 根据项目要求切换 JDK
if defined PROJECT_JAVA_VERSION (
echo Detected project Java version: %PROJECT_JAVA_VERSION%
call switch_jdk.bat %PROJECT_JAVA_VERSION%
) else (
echo No specific Java version detected, using default
)
REM 启动开发环境
cmd /k
9.3.2 Git Hook 集成
#!/bin/sh# .git/hooks/post-checkout# Git 切换分支后自动切换 JDK 版本# 🚀 实用技巧:Git Hook 自动化,每次切换分支自动设置对应的 JDK 版本if [-f .jdkversion ]; then
JDK_VERSION=$(cat .jdkversion)
echo"Switching to JDK $JDK_VERSION for this project"# Windows 环境调用批处理脚本if ["$OS"="Windows_NT"]; then
cmd //c "switch_jdk.bat $JDK_VERSION"fifi
9.4 团队协作建议
9.4.1 统一配置文件
在项目根目录创建 jdk.config:
# JDK Configuration for Project[project]name=MyProject
required_jdk=17fallback_jdk=11[paths]windows=C:\Java\jdk-17linux=/usr/lib/jvm/java-17-openjdk
macos=/usr/local/java/jdk-17[maven]java.version=17maven.compiler.source=17maven.compiler.target=17