条件 Java 编译
我是一名资深 C++ 程序员,刚接触 Java。我正在 Eclipse 中开发 Java Blackberry 项目。问题 - 有没有办法在项目中引入不同的配置集,然后根据这些配置集编译略有不同的代码?
在Visual Studio中,我们有项目配置和#ifdef;我知道 Java 中没有 #ifdef,但也许是文件级别的东西?
I'm a longtime C++ programmer, new to Java. I'm developing a Java Blackberry project in Eclipse. Question - is there a way to introduce different configuration sets within the project and then compile slightly different code based on those?
In Visual Studio, we have project configurations and #ifdef; I know there's no #ifdef in Java, but maybe something on file level?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(11)
如果您想要专门用于 BlackBerry,BlackBerry JDE 有 预处理器:
你
可以为您启用预处理
通过更新 Eclipse™ 应用程序
配置文件。<块引用>
在 C:\Program Files\Eclipse\configuration\config.ini 中,
添加以下行:
osgi.framework.extensions=net.rim.eide.preprocessing.hook
如果您在之后启用预处理
已经构建完毕,您必须清理
之前从项目菜单中进行项目
您再次构建该项目。
然后您可以在代码中执行以下操作:
//#ifdef SOMETHING
// do something here
//#else
// do something else
//#endif
有关详细信息,请参阅 指定预处理器定义
可以说这是一个穷人ifdef
:http: //www.javapractices.com/topic/TopicAction.do?Id=64?
您可以将 Maven 的资源过滤与公共静态最终字段结合使用,这确实会被有条件地编译。
private static final int MODE = ${mode};
...
if (MODE == ANDROID) {
//android specific code here
} else {
}
现在你需要向你的maven pom添加一个名为“mode”的属性,它应该是
与您的 ANDROID 常量具有相同的值。
java编译器应该(!)删除if和else块,从而留下你的android代码。
不是测试集,所以没有保证,我更喜欢配置而不是条件编译。
在 Eclipse 中,您可以使用多个项目
- Main(包含通用代码)
- Version1(包含 version1 代码)
Version2(包含 version2 代码)
- 主要 ->选择项目 -> 属性 -> Java 构建路径 -> 项目选项卡
- 选择添加...
- 将“Version1”xor“Version2”添加回工作区,然后单击“确定”。
版本 1 和版本 2 包含相同的文件,但实现不同。在 Main 中,您通常会编写例如
import org.mycustom.Version;
,如果您包含 Version1/Version2 项目作为参考,它将使用 Version1/Version2 项目中的 Version.java 文件进行编译。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您可以设置“final”字段和 ifs 以使编译器优化编译后的字节码。
如果在编译代码时“myFinalVar”为 false,则编译后的类中将会丢失“do some....”位。如果您有多个条件 - 可以稍微整理一下:将它们全部转移到另一个类(例如“Config.myFinalVar”),然后所有条件都可以保存在一个整齐的地方。
此机制在'Hardcore Java'。
[实际上我认为这与之前发布的“穷人的 ifdef”机制相同。]
You can set up 'final' fields and ifs to get the compiler to optimize the compiled byte-codes.
If 'myFinalVar' is false when the code is compiled the 'do something....' bit will be missed out of the compiled class. If you have more than one condition - this can be tidied up a bit: shift them all to another class (say 'Config.myFinalVar') and then the conditions can all be kept in one neat place.
This mechanism is described in 'Hardcore Java'.
[Actually I think this is the same mechanism as the "poor man's ifdef" posted earlier.]