Set an environment variable within a shell alias

Answering your isolated example:

when you do something like this:

bar=foo my_command

then bar is set in my_command's environment (and is not seen by the current shell). Hence, when you do:

bar=stuff
bar=foo my_command "$bar"

since the expansion of $bar occurs before my_command is executed, then it's like doing:

bar=foo my_command stuff

since the $bar is expanded before my_command is forked. That explains the [blank line] you obtain in your example:

$ alias foo='BAR=baz'
$ type foo
foo is aliased to `BAR=baz'
$ foo echo $BAR
[blank line]

Just for fun, try these:

$ alias foo=BAR=baz
$ BAR=something
$ foo echo "$BAR"
something

makes sense?

$ alias foo=BAR=baz
$ foo eval 'echo "$BAR"'
baz

this is because BAR is passed in eval's environment, and then echo "$BAR" is expanded… with the expected value (note the single quotes!).

Similarly,

$ alias foo=BAR=baz
$ foo sh -c 'echo "$BAR"'
baz

The jdk1.7.*.jdk bit is probably the problem. If I put an explicit version in it works fine

You can use /usr/libexec/java_home -v 1.7 to get the latest 1.7 version installed.

So to redo your alias, try:

alias j7='JAVA_HOME=`/usr/libexec/java_home -v 1.7`'

Note the back ticks around the java_home bit which will then execute the command to generate the correct path to set JAVA_HOME to.