一、熟悉一下问题来龙去脉
转载自 点击
环境:
jdk 1.6;
jboss 5.1.0.GA
eclipse 4.2
这里可以配置的jdk,还有个java compiler中可以配置compiler level(如图中红色框)。这两个东西就是这个问题的关键。
在eclipse中进行开发的时候,build path 中JDK进行类库的编译(就是你使用类在不在这个JDK中),java compiler compliance level是对这个项目语法的编译(就是你的项目中语法的正确与否),也可以把java compiler compliance level中配置的编译版本号的作用看作是你这个项目将来开发完毕之后,要放到服务器上运行,那个服务器上JDK的运行版本。
而我的问题就出在build path中配置1.6的JDK,java compiler compliance level中配置的1.7(因为以前我用过一段时间1.7)
而在jboss服务器上是1.6的JDK,就报了那个错误,说是编译所用的jdk(1.7)比运行所用的jdk(1.6)高了,这是错误的。
放在其他人机器上之所以不报错,是因为他的jboss使用的jdk恰恰是1.7。这个版本是向下兼容的。
再拿个被人举过的例子,如果JDK1.4不能使用泛型。而java compiler compliance level设置的是你写好的JAVA代码按照什么JDK版本级别编译,例如:设置的是1.4,编译出来的class文件可以在1.4以上的JRE上运行,如果用的是5.0级别编译,就不能运行在1.4的环境里面,会提示版本过高。
总结:
1、在开发和部署过程中,最安全的做法,是build path , java complier compliance level,jboss服务器配置的JDK都保持一致,就不会出现任何问题的。
2、我们常常关注build path中jdk的版本和jboss中jdk版本,殊不知他们是通过 java complier compliance level联系起来的。
有时候我们并不能仅仅按照网上的解决步骤把问题解决了就算万事大吉了。我不得不承认这是解决问题的捷径,但从捷径走过后,我们应分析和总结问题的来龙去脉,真正理解它的本质,才算是一种积累,因为网上的解决方案永远是针对过时的技术,新技术暴露的问题依然会让你手足无措,但幸好技术的本质是不容易改变的,所以说,抓住本质,才是常胜之道。
二、各路说法
2.1 java compiler compliance leve 是为了兼容在目标服务器上面运行
Not quite. But first of all, each project has the option to set its own language levels or (default) inherit them from the workspace settings. Saves having to tailor each project minutely in cases where you don't care.
When you say "source compliance level" and "generated class code level", you're setting the options for the selected JDK to compile with, not selecting the JDK itself (which is a completely different option).
In other words, you're doing something like "/usr/java/jdk1.6/bin/javac -source 1.4 XXXXFile.java", not switching to JDK 1.4. However, by setting the JDK 1.4 source level, the 1.6 compiler knows, for example, that "enum" is a valid variable name (as it was in JDK 1.4 and earlier) and not a reserved word (JDK 1.5 and later).
(enum在1.6编译的时候就报错,这个例子就是我在项目中遇见的问题)
This is where Java shows that it was designed for Enterprise use. A certain other platform I could mention lacks those options, and if you need legacy support in an emergency, well, tough luck.
Obviously, it's one thing to be backwards compatible, and another to be prescient, so while you can declare 1.4 compatibility mode on the 1.6 JDK, you can't declare 1.6 compatibility mode on JDK 1.4.
There's more than just one reason why Eclipse supports multiple JDKs, however. While legacy code occasionally does end up requiring the actual 1.4 compiler rather than 1.6 running in 1.4 mode, you may also have things like 1.6.0_u10 and 1.6.0_u20 JDKs installed at the same time. Say, for example, where there's a project that happens to crash the 1.6.0_u20 VM when you debug it, so you have to fall back to the 1.6.0_u10 version (these aren't necessarily real JVM names, but you get the idea, I hope!).
来源:oschina
链接:https://my.oschina.net/u/2308739/blog/602319