Macros in Java?

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

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

Both foo classes have the same method One of them is from a third party library I think I can easily switch to the default library by changing the single line code Is that possible?

Editor: these two classes are not under my control (one is from sqlcipher of Android project and the other is from Android SDK) I need this because the sqlcipher library doesn't work on Samsung phones at present

Solution

No, there is no commonly used preprocessor in Java (although you can use C preprocessor in Java code, I will block it because it will be very unusual and destroy most tools for processing code) This choice is usually done at run time, not at compile time in Java

The usual Java method is to let two classes implement the same interface and reference them through the interface:

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();
}

If this is not possible (for example, if at least one foo class is not under your control), you can achieve the same effect through an abstract foowrapper class (or interface) and two different implementations (xyzfoowrapper, abcfoowrapper)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>