验证Java版本兼容性 [英] Verify java version compatibility
问题描述
我有一个使用jdk 1.7编译的jar文件,我想在加载期间检查我的jar运行的Java运行时环境是1.7还是更高版本.有办法吗?
I have a jar file compiled using jdk 1.7, I'd like to check during load time that the java runtime environment my jar is running under is 1.7 or newer. Is there a way to do that?
我尝试使用System.getProperty("java.version"),但这没有帮助,因为我的类版本是51,而jre 1.6拒绝加载它.
I tried using System.getProperty("java.version") but that didn't help since my class version was 51 and jre 1.6 refuse to load it.
推荐答案
我有相同的要求,并通过以下方式解决了该问题:
I have the same requirement and I solved it the following way:
具有一个启动"类,该类绝对不依赖于(=导入)任何新的JDK类或您的应用程序的任何类.您不按名称导入您的主班!
Have a "startup" class that has absolutely no dependencies (=imports) to any new JDK class or to any of your application's classes. You man not import your main class by name!
类似:
在该启动程序类中,检查所需的Java版本.
Inside that starter class, check the Java version that you need.
如果检查成功,则使用反射加载您的主类并启动它的main方法(或您使用的任何方法).像这样:
If the check is successful then load your main class using reflection and start it's main method (or whichever method you use). Something like this:
public class MyStarter
{
public static void main(String[] args)
{
String version = System.getProperty("java.version", null);
boolean isVersionOK = ... ;
if (!isVersionOK)
{
System.err.println("Wrong Java version detected");
// or display some messagebox using JOptionPane
System.exit(1);
}
Class mainClass = Class.forName("com.foo.MyMain");
Method main = mgr.getDeclaredMethod("main", new Class[] { String[].class });
main.invoke(null, new Object[] { args });
}
}
再次:确保MyStarter不包含任何导入到您的应用程序或Java 1.2(或您要定位的任何Java版本)中不可用的类.
Again: make sure MyStarter does not contain any imports to your application or classes that are not available in Java 1.2 (or whatever Java version you will target).
然后使用 -source 1.2 -target 1.2
编译 MyStarter
(并且仅该类)使用常规编译器编译其余的类(例如,创建Java7 .class文件).
Then compile MyStarter
(and only that class) with -source 1.2 -target 1.2
Compile the rest of your classes with the regular compiler (e.g. creating Java7 .class files).
如果生成可执行jar,则将 com.foo.MyStarter
添加为 Main-Class:
属性.
If you generate an executable jar, then add com.foo.MyStarter
as the Main-Class:
attribute.
我的Ant build.xml
中的编译"目标看起来像这样:
My the "compile" target in my Ant build.xml
looks something like this:
<-- compile the starter class for Java 1.2 -->
<javac destdir="${build}"
srcdir="${src}"
target="1.2"
source="1.2"
encoding="ISO-8859-1"
includeantruntime="false"
includes="com/foo/MyStarter.java"/>
<-- compile the rest with for Java 1.6 -->
<javac destdir="${build}"
srcdir="${src}"
target="1.6"
source="1.6"
includeantruntime="false"
encoding="ISO-8859-1">
<exclude name="com/foo/MyStarter.java"/>
<classpath>
....
</classpath>
</javac>
然后将所有内容放入一个jar文件中.
Then put everything into one jar file.
这篇关于验证Java版本兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!