Java compiler under Eclipse/Ant defaults to %JAVA_

2019-07-11 04:35发布

问题:

I recently encountered a build environment behavior that I need to better understand:

Overview of my freshly installed workstation:

  1. Installed jdk1.6.0_45, then jdk1.7.0_80, then jdk1.8.0_131.
  2. %JAVA_HOME% is set to C:\Program Files\Java\jdk1.8.0_131\
  3. Installed Eclipse Kepler (4.3.2)
  4. I then manually (by way of unzipping) added to C:\Program Files\Java the following: jdk1.7.0_45, jre1.7.0_76, jre1.7.0_79.
  5. Checked out a legacy Ant-based project, designed to run under JRE7 only.

My Eclipse's Window > Preferences > Java > Installed JREs now looks:

Execution environments are standard (i.e. I have not added any):

Now, when I right-click the project's build.xml and run that Ant Build... I can see that an execution environment that uses jre7 (jdk1.7.0_80) as its default, is selected:

So, when I click Apply, then Run, it will use a Java 7 compiler, right?

Wrong. For some strange reason, all .class files generated by this build have a major_version of Java 8!

I solved this problem by brute-forcing Ant to use Javac 1.7, via build.xml:

<property name="ant.build.javac.source" value="1.7"/> 
<property name="ant.build.javac.target" value="1.7"/>

My question is: Why would a build in Eclipse running under JDK8 default to JRE8 despite Execution Environment set to JDK7?

IOW, is this a documented feature? If so, where can I learn more about this?


Update:

Thanks to the answer below, I tried to verify the role of %JAVA_HOME% in Ant's execution. Externally changing my workstation's %JAVA_HOME% system variable would be defeating the purpose of my setup, so I tried changing %JAVACMD% only. That didn't help. So, I echoed relevant env vars in my build.xml:

<target name="jdk_version_validation">
    <echo message="Java Version: ${java.version}" />
    <echo message="Java home: ${java.home}" />
    <echo message="JAVA_HOME: ${env.JAVA_HOME}" />
    <echo message="JAVACMD: ${env.JAVACMD}" />
</target>

and this is what I got:

jdk_version_validation:
     [echo] Java Version: 1.7.0_80
     [echo] Java home: C:\Program Files\Java\jre7
     [echo] JAVA_HOME: C:\Program Files\Java\jdk1.8.0_131\
     [echo] JAVACMD: C:\Program Files\Java\jdk1.7.0_80\bin

Without the brute-force property overriding described above, this still produces Java 8 class files. Amazing.

回答1:

A lot of those things you list appear to be JREs (which don't contain a javac compiler). So Ant is probably falling back on using the 1.8 JDK listed in JAVA_HOME.

You could try using the JavaSE-1.7 Execution Evironment and actually select the one JDK you have as the default in the 'Compatible JREs' list.