java 条件编译
方式1. 使用if条件编译
原理:jvm 会对if(false)中的代码做优化:
例如:
public static void main(String[] args) {
if(false){
System.out.println("hello world");
}
System.out.println("main");
}
编译之后的源码:
public static void main(String[] args) {
System.out.println("main");
}
基于上述原理,可以通过动态的修改变脸的值达到条件编译的目的;
方式2:manifold预编译
使用说明:
http://manifold.systems/docs.html#setup
1. 下载idea插件 Manifold
项目本身是开源免费的,但是插件是收费的,10天免费试用期
插件费用:$19.9/M -> $199/Y $159/2nd year
参考文档:manifold-preprocessor
2. 修改maven配置信息
<properties>
<!-- java条件编译 -->
<manifold.version>2021.1.34</manifold.version>
</properties>
<dependencies>
<dependency>
<groupId>systems.manifold</groupId>
<artifactId>manifold-ext-rt</artifactId>
<version>${manifold.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- java Manifold 条件编译 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>8</source>
<target>8</target>
<encoding>UTF-8</encoding>
<compilerArgs>
<!-- Configure manifold plugin -->
<arg>-Xplugin:Manifold</arg>
</compilerArgs>
<!-- Add the processor path for the plugin -->
<annotationProcessorPaths>
<path>
<groupId>systems.manifold</groupId>
<artifactId>manifold-preprocessor</artifactId>
<version>${manifold.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
编写测试类:
#define MY_API_1
#if MY_API_1
import java.util.Date;
#else
import java.time.LocalDateTime;
#endif
public class ServiceManifold #if MY_API_2 implements Serializable #endif {
#if MY_API_1
public void setDate(Date date) {
System.out.println(date);
}
#elif MY_API_2
public void setDate(LocalDateTime date){
System.out.println(date);
}
#endif
}
使用maven编译,生成之后的java代码:
package com.jd.gxf.gfkj.qrcode.service;
import java.util.Date;
public class ServiceManifold {
public ServiceManifold() {
}
public void setDate(Date date) {
System.out.println(date);
}
}
当启用 MY_API_2之后,编译的源码如下:
package com.jd.gxf.gfkj.qrcode.service;
import java.io.Serializable;
import java.time.LocalDateTime;
public class ServiceManifold implements Serializable {
public ServiceManifold() {
}
public void setDate(LocalDateTime date) {
System.out.println(date);
}
}
参考资料: