问题
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, e.g., 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.
回答1:
I see a couple of options:
- 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.
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!
回答2:
I think you can use System properties (http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html) in order to discover which Java version is beind used, and then you could adapt your application to run accordingly.
来源:https://stackoverflow.com/questions/17252454/best-practice-for-developing-under-multiple-jdks