Setting Current JDK programmatically on Mac

A few days back I was looking for a way to change the CurrentJDK symbolic link on my Mac. I had found this nice script somewhere (don’t quite remember where). But is is very useful.

#!/bin/sh

cd /System/Library/Frameworks/JavaVM.framework/Versions

CURJDK="`readlink CurrentJDK`"echo Current JDK version: $CURJDK

if [ "$1" == "" ]; thenecho Installed versions:lsexitfi

VERFOUND=`ls | grep $1 | head -n 1`

if [ "$VERFOUND" != "$1" ]; thenBASE="`basename $0`"echo Error: Could not change JDK-- version $1 not installed!echo Run $BASE without arguments to see a list of installed versions.exit 127fi

echo You must now enter your Mac OS X password to change the JDK.sudo ln -fhsv $1 CurrentJDK

Save it as a file name of your choice. I saved it as “SetJDK.sh”. Give it execute permissions, and run the script.

7 thoughts on “Setting Current JDK programmatically on Mac”

  1. I have that same script, not sure where I got it too, but it works great.
    Can I ask how you run it? I have to open the file in pico, then to copy and paste it in the terminal, and then run it. I would be easier to just run it.

    I am a newbie at this, but do you just add the ".sh" to it?

    Thanks,
    John

  2. Hi John.

    To run it, go to the directory where you’ve saved it, and then put a period and forward slash, followed by the name of the script.

    So in my case to run it I’d do ./SetJDK.sh

    And oh, make sure you have permissions to execute the script as well.

  3. I had the file named SetJDK and re named it to SetJDK.sh,and I moved into my home directory,a nd apply the "./SeJDK.sh" and this works, thank you so much. I know see to run the script I use the "./" this is great`-`

    Thanks again
    John

  4. Don’t worry about where CurrentJDK points. It’s really just a backwards-compatibility anachronism. To get the top JVM in Java Preferences, use the /usr/libexec/java_home tool. See the “java_home” man page for more info.

  5. @Mike Swingler, CurrentJDK is still used by the latest Maven releases, so if you aren’t careful, you can be accidentally compiling code with the wrong JDK version. I discovered this when trying to get the Jaxb1 plugin (which doesn’t fork to a separate JVM) to compile an XSD which used some Java 6 compile classes.

Leave a Reply

Your email address will not be published. Required fields are marked *