21

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
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
user1495174
  • 211
  • 1
  • 2
  • 3

7 Answers7

21

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()
}
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 2
    This would only really be of benefit if both Dates implemented a common interface. – gdw2 Oct 18 '13 at 22:58
  • Say if both of those libraries were external JARs. Would the compiler include both of those JARs in the compiled code if `useSql` was `static final`? – Mapsy May 08 '17 at 16:35
  • Yes. it will. however you still need to provide it during runtime – jmj May 09 '17 at 04:57
5

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.

Scoopta
  • 987
  • 1
  • 9
  • 22
2

We don't have conditional import in java

Pramod Kumar
  • 7,914
  • 5
  • 28
  • 37
1

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.

serv-inc
  • 35,772
  • 9
  • 166
  • 188
Yair Zaslavsky
  • 4,091
  • 4
  • 20
  • 27
1

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
Igor Maznitsa
  • 833
  • 7
  • 12
1

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()
 }
Abdelaty
  • 11
  • 4
0

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.

LadyCailin
  • 849
  • 10
  • 26