'Java conditional imports

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


Solution 1:[1]

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

Solution 2:[2]

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.

Solution 3:[3]

We don't have conditional import in java

Solution 4:[4]

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

Solution 5:[5]

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.

Solution 6:[6]

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.

Solution 7:[7]

Java Does't support conditional import .

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jmj
Solution 2 Scoopta
Solution 3 Pramod Kumar
Solution 4 Igor Maznitsa
Solution 5 serv-inc
Solution 6 LadyCailin
Solution 7 Sumit Singh