Java compiler under Eclipse/Ant defaults to %JAVA_HOME%?

社会主义新天地 提交于 2019-12-12 21:04:49

问题


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.



来源:https://stackoverflow.com/questions/44306338/java-compiler-under-eclipse-ant-defaults-to-java-home

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!