简体   繁体   中英

How to prevent Java to compile parts of code for newer SDK?

I want to make a code that works for Java 1.8 and 1.7. Specifically, I want to implement a static method in the interface. This is allowed in java 8 but not in 7. I read there is a way pipe C macros, also that this is not good practice. Additionally, piping the macros do not tell me which SDK is being use?

So there is any "good" solution to this?

UPDATE :

Please do not suggest implement an abstract class. Thanks.

NO DUPLICATE

Can Java 8 code be compiled to run on Java 7 jvm? asks if there is a way by command line to compile the code of java 1.8 in 1.7. At least the answer looks so. The question I do, it is if there is a way to indicate in the code which parts are from the code belongs to 1.8 and what to 1.7.

There is no clean Java way to do this. There are several ways (which you can also combine) to implement this. The core of the solution is a small code generator which can generate the code that you need. You have to configure your build system to invoke the generator before javac is called.

  1. Put the code into different files (header, footer, Java 8 code) and create the final Java class in a prepare step of your build system (just concatenate the parts which you need). For Maven, that would be generate-sources . For Ant, use a set of targets.
  2. Put the code into the same file and use magic comments to specify where the code starts and ends. The code itself is commented out with line comments in the first column:

     /*!!!JAVA8-START!!!*/ //...Java 8 code... /*!!!JAVA8-END!!!*/ 

    If your build system detects Java 8, it can search for lines which begin with // between the two comments and remove the // .

  3. If you use Maven, you can have three modules. A common module which contains the non-Java 7/8 specific code. One module for Java 7 and one for Java 8. Enable the specific modules with a build profile . Use a unit test to make sure that the code in the Java 7 and 8 modules is the same (for example by removing the Java 8 specific parts and comparing the rest to Java 7).

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