How to have conditional imports in Java like we have the ifdefs
in C
This is what I intend to achieve
ifdef TEST
import com.google.mystubs.swing;
elif
import javax.swing.*;
endif
How to have conditional imports in Java like we have the ifdefs
in C
This is what I intend to achieve
ifdef TEST
import com.google.mystubs.swing;
elif
import javax.swing.*;
endif
You don't have conditional import with 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()
}
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.
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.
This blog provides some information.
Java Comment Preprocessor supports 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
//#ifdef FLAG
//+prefix
import some.class.Clazz;
//-prefix
Clazz.call();
//#endif
instead of doing this:
import com.test.example.interceptorModule
{
example().intercepte();
}
I figured out that we can call the class using it's path like this
com.test.example.interceptorModule().intercepte()
so to import the above class conditionally you can do this:
if(!intercepting)
{
com.test.example.interceptorModule().intercepte()
}
What you're trying to do is a valid idea, but you should use mocks instead. Mockito is a great library for that.
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.