Java 条件导入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11288083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java conditional imports
提问by user1495174
How to have conditional imports in Java like we have the ifdefs
in C
This is what I intend to achieve
如何像我们ifdefs
在 C 中那样在 Java 中进行条件导入这是我打算实现的
ifdef TEST
import com.google.mystubs.swing;
elif
import javax.swing.*;
endif
回答by Jigar Joshi
You don't have conditional import with java
您没有使用 java 进行条件导入
But you could conditionally use different classes with same name using fully qualified name
但是您可以使用完全限定名称有条件地使用具有相同名称的不同类
for example:
例如:
if(useSql){
java.sql.Date date = new java.sql.Date()
}else{
java.util.Date date = new java.util.Date()
}
回答by Pramod Kumar
We don't have conditional import in java
我们在 Java 中没有条件导入
回答by Yair Zaslavsky
There is no support for this at Java.
Bear in mind that #IFDEF is done at pre-processor stage at C++ - No support in Java for that.
What you can try and have is something like an annotation processor, prior to the days annotations were introduced in JDK 1.5.
In addition, you can use annotations to be processed during compile time.
Thisblog provides some information.
Java 不支持此功能。
请记住,#IFDEF 是在 C++ 的预处理器阶段完成的 - Java 不支持。
在 JDK 1.5 中引入注释之前,您可以尝试并拥有类似注释处理器的东西。
此外,您可以使用注释在编译时进行处理。
这个博客提供了一些信息。
回答by LadyCailin
What you're trying to do is a valid idea, but you should use mocks instead. Mockitois a great library for that.
您尝试做的是一个有效的想法,但您应该使用模拟。Mockito是一个很棒的库。
The paradigm is a bit different, but you should look into unit testing with a mocking library and get an understanding of that, which will allow you to do what you're trying, in a better (in my opinion) way.
范式有点不同,但您应该研究使用模拟库进行单元测试并对此有所了解,这将使您能够以更好(在我看来)的方式做您正在尝试的事情。
回答by Igor Maznitsa
Java Comment Preprocessorsupports prefix and postfix sections in result document and it is very useful to form class import section, you can place import string even in middle of your class
Java注释预处理器支持结果文档中的前缀和后缀部分,形成类导入部分非常有用,您甚至可以在类中间放置导入字符串
//#ifdef FLAG
//+prefix
import some.class.Clazz;
//-prefix
Clazz.call();
//#endif
回答by Scoopta
You could use a traditional if statement and then instead of importing do Class.forName("example.ExampleClass")
That would return a Class
object which you could then invoke Class.newInstance()
on. It would allow you to avoid compile time errors for dependencies that may not exist as well as do something that's similar to conditional importing.
您可以使用传统的 if 语句,而不是导入 do Class.forName("example.ExampleClass")
That 将返回一个Class
您可以调用的对象Class.newInstance()
。它将允许您避免可能不存在的依赖项的编译时错误,以及执行类似于条件导入的操作。
回答by Sumit Singh
Java Does't support conditional import
.
Java 不支持条件import
.