简体   繁体   中英

Best practice for developing under multiple JDKs

I have a library which I am currently developing with target compatibility to JDK 6. I like to take advantage of Java 8 feature, like lambdas. The code and APIs will greatly profit from Java 8.

I would like to offer versions of the library for Java 6 and Java 8, eg, where a certain part is only available in the Java 8 version.

Now there are a few core classes which might have their different source version (the legacy Java 6 version and the new Java 8 version).

What is the best practice of doing this? In Objective-C or C++ I would consider using a preprocessor directive.

I see a couple of options:

  1. Package different versions of your library, one for JDK6 and one for JDK8. Users are responsible for including the right one for their application. This will be an interesting build to do. If you're using Maven, I think you'll just use 3 projects; a "commons" project with all common classes, a "JDK6" project that has the commons project as a dependency and builds the JDK6 jar, and then a "JDK8" project that has the commons project as a dependency and builds the JDK8 jar. One attractive bit of this approach is that it obviously works, and you have no hard maintenance to do.
  2. Package both the JDK6 and the JDK8 version in the same JAR, and create a "Runtime"-type class that's responsible for creating the proper versions of your library's objects at runtime depending on the JDK it's running in. For example:

     public abstract class Runtime { private static Runtime instance; public static Runtime getInstance() { if(instance == null) { try { if(System.getProperty("java.version").startsWith("8")) instance = Class.forName("com.yourcompany.libname.runtime.Runtime8").newInstance(); else instance = Class.forName("com.yourcompany.libname.runtime.Runtime6").newInstance(); } catch(Exception e) { throw new RuntimeException("Could not create runtime", e); } } return instance; } public abstract Framework getFramework(); } 

    Using this approach, you would only need to use reflection to load the initial "Runtime" object, and then you could use native Java for everything else. For example:

      Framework framework=Runtime.getInstance().getFramework(); ModelObject1 m=framework.newModelObject1(); // ... 

    Just be SURE your Runtime6 class doesn't refer to a JDK8 class, even transitively via imports. The main drawback to this approach is tracking that little tidbit over time.

I think what you're doing is interesting, and I'm very curious to hear how you choose to get it done. Please keep us posted!

我认为您可以使用系统属性( http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html )来发现使用了哪个Java版本,然后可以使应用程序适应运行因此。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM