Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify java version compatibility

Tags:

java

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?

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.

like image 986
user2512495 Avatar asked Jun 27 '13 15:06

user2512495


1 Answers

I have the same requirement and I solved it the following way:

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!

Something like:

Inside that starter class, check the Java version that you need.

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 });
   }
}

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).

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).

If you generate an executable jar, then add com.foo.MyStarter as the Main-Class: attribute.

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>

Then put everything into one jar file.

like image 120
a_horse_with_no_name Avatar answered Sep 23 '22 22:09

a_horse_with_no_name