Verify java version compatibility

I have a jar file compiled with JDK 1.7. I want to check whether the Java runtime environment of my jar is 1.7 or updated when loading Is there any way to do this?

I try to use system Getproperty ("Java. Version"), but it doesn't help because my class version is 51 and JRE 1.6 refuse to load it

Solution

I have the same request, and I solved it in the following ways:

There is a "startup" class that has no dependencies on any new JDK class or any application class (= imports) Don't import your main class by name!

It's like:

In this starter class, check the required java version

If the check is successful, use reflection to load the main class and start its main method (or any 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 message@R_224_2419@ 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 that mystarter does not contain any classes imported into your application or unavailable in Java 1.2 (or any Java version you will locate)

Then compile mystarter (and only that class) with - source 1.2 - target 1.2, and compile the rest of the classes with a regular compiler (for example, create a java7. Class file)

If the executable jar is generated, com foo. Mystarter is added as main class: attribute

My ant build The "compile" target in XML looks 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 a jar file

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>