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