【发布时间】:2014-12-26 18:45:40
【问题描述】:
我开发了一个可以在两个不同平台上运行的 Java 库。要打印消息,一个平台使用printA(str) 方法,而另一个平台使用printB(str) 方法。在 C++ 中,我会创建一个静态方法:
public static void print(string str)
{
#ifdef platformA
printA(str);
#else
printB(str);
#endif
}
由于 Java 没有#ifdef,因此它成为一项棘手的任务。我开始研究用静态方法覆盖抽象类,但不确定我是否走对了方向。最优雅的方法是什么?
编辑:在 Andy Thomas 的回答下(谢谢!)我找到了适合我的解决方案。唯一的缺点 - 它必须在启动时初始化。下面是代码。 公共库:
//interface is only for internal use in Output class
public interface IPrintApi
{
public void Print(String message);
}
public abstract class Output
{
private static IPrintApi m_api;
public static void SetPrintAPI(IPrintApi api)
{
m_api=api;
}
public static void MyPrint(String message)
{
m_api.Print(message);
}
}
该函数的调用在普通库和平台代码中是一样的:
public class CommonTest
{
public CommonTest()
{
Output.MyPrint("print from library");
}
}
每个平台的代码都必须具有特定于平台的接口实现,例如平台A(对于B是相同的):
public class OutputA implements IPrintApi
{
public void Print(String message)
{
//here is our platform-specific call
PrintA(message);
}
}
用法:
public class AppPlatformA
{
public static void main(String[] args)
{
// point the abstract Output.Print function to the available implementation
OutputA myPrintImpl = new OutputA();
Output.SetPrintAPI(myPrintImpl);
// and now you can use it!
Output.MyPrint("hello world!");
}
}
【问题讨论】:
-
[stackoverflow.com/questions/228477/…我想这对你有帮助。
-
这不是运行时检测的问题,更多的是避免编译时问题的代码设计:我在platformB中使用库时没有定义printA,反之亦然...跨度>
标签: java import conditional conditional-compilation