简体   繁体   中英

Two implementations for two different Java versions

I'm asked to make a Java app. It is meant to run on a Debian server. The thing is that:

  • This server uses Debian 7 (wheezy) which has Java 6 and Java 7
  • The server should be updated soon to a newer version that will have Java 8

There are many places in the code where using a stream would be great, instead of using a good old for loop. Though, this isn't supported in Java <= 7.

So my question is: is there any way to have two implementations of a class, one for Java <= 7 and one for Java >= 8? The choice would be made at compile time depending on the compiler (JDK 7 would compile the Java7 version and JDK 8 would compile the Java8 version).

By the way, I'm asking this regardless of the actual problem. It's a question that I find interesting, I know it's something that can be done in Android (to target different API levels) but I'm not sure it's possible in pure Java.

Thank you in advance

That is theoretically possible but not so simple. You would be well advised to write code in java 7 standard so it would be backwards compatible. However, if you still want to write 2 classes: You will need to write each class in separate project and compile them (each in correct jdk version) to be in different jars. Then you will need to write your own classloader that would load appropriate jar based on your jvm version. I'd definitely say it's not worth it

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