Verify java version compatibility

后端 未结 4 1367
一整个雨季
一整个雨季 2021-01-05 19:44

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

4条回答
  •  孤城傲影
    2021-01-05 20:03

    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 -->
      
    
    <-- compile the rest with for Java 1.6 -->
    
      
      
          ....
      
    
    

    Then put everything into one jar file.

提交回复
热议问题