Java中的宏? [英] Macros in Java?

查看:213
本文介绍了Java中的宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Java中没有宏,但是有一种解决方法可以执行以下操作:

I know there are no macros in Java, but is there a workaround to do something like this:

#ifdef _FOO_FLAG_
import com.x.y.z.Foo;
#else
import com.a.b.c.Foo;
#endif

两者 Foo 类有相同的方法。其中一个来自第三方图书馆。我希望能够通过更改单行代码轻松切换到默认库。这可能吗?

Both Foo classes have the same methods. One of them is from a 3rd party library. I want to be able to switch to default library easily by changing a single line of code. Is this possible?

编辑:

这两个课程都不受我的控制(其中一个来自SQLCipher for Android项目,另一个来自Android SDK)。我需要这个,因为SQLCipher库目前在SAMSUNG手机上不起作用。


Both classes are out of my control(one of them is from SQLCipher for Android project, other one is from Android SDK). I need this because SQLCipher library doesn't work on SAMSUNG phones at the moment.

推荐答案

不,没有常用的预制Java中的处理器(虽然你可以在你的Java代码上使用C预处理器,但我不鼓励它,因为它会非常不寻常并且会破坏大多数处理代码的工具)。这些选择通常在运行时完成而不是在Java中编译时。

No, there is no commonly used pre-processor in Java (although you could use the C preprocessor on your Java code, but I'd discourage it, as it would be very unusual and would break most tools that handle your code). Such selections are usually done at runtime rather than compile-time in Java.

通常的Java方法是让两个类都实现相同的界面,仅通过界面引用它们:

The usual Java-way for this is to have both classes implement the same interface and refer to them via the interface only:

IFoo myFoo;
if (FOO_FLAG) { // possibly a public static final boolean
  myFoo = new com.x.y.z.Foo();
} else {
  myFoo = new com.a.b.c.Foo();
}

如果这是不可能的(例如,如果至少有一个 Foo 类不受你的控制),然后你可以通过一个抽象的 FooWrapper 类(或接口)实现相同的效果两种不同的实现( XYZFooWrapper ABCFooWrapper )。

If this is not possible (for example if at least one of the Foo classes is not under your control), then you can achieve the same effect by an abstract FooWrapper class (or interface) with two different implementations (XYZFooWrapper, ABCFooWrapper).

这篇关于Java中的宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆