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" == "" ]; then
echo Installed versions:
ls
exit
fi

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

if [ "$VERFOUND" != "$1" ]; then
BASE="`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 127
fi

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.

Comments

John Barrett

John Barrett wrote on 09/17/07 6:12 PM

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
Indy Nagpal

Indy Nagpal wrote on 09/19/07 10:43 PM

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.
John Barrett

John Barrett wrote on 09/22/07 3:55 PM

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
Mike Swingler

Mike Swingler wrote on 07/10/09 6:00 PM

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.
Josh

Josh wrote on 08/27/09 7:57 AM

@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.
Mike Swingler

Mike Swingler wrote on 08/27/09 8:04 AM

If Maven isn't listening to the $JAVA_HOME environment variable (like Ant, and most of the others do), that is just lame.
andy

andy wrote on 10/30/09 7:38 AM

instead of using this script run the java preferences application in applications/utilities

Leave a comment

Tell us about yourself
(required field)
(required field)
Comment and preferences
Leave this field empty: