As mentioned before, you can use static imports like:
import static DataGen.*;
This is not a great idea, though. It will essentially take everything from DataGen
and stick it in your main class. Since DataGen
consists entirely of static methods and fields, you are destroying almost the whole point of having DataGen
be a separate class. The only reason for DataGen
to exist is to provide a slight bit of organization to your methods and fields.
To quote from this answer:
The static import feature...has negative consequences to readability and testability:
- You dump the content of a potentially large class into your current namespace, making your code harder to read; modern IDEs mitigate this by letting you navigate to the definition of the object by clicking its name in a program.
- Your code relies upon static objects, making it extremely hard to test. For example, you cannot easily drop a mock logger, and expect your code start using it. This is a general limitation of using static objects, though - you get it when you use static objects, with or without the static import.
A better way is by only importing what you need:
import static DataGen.OPTION1;
import static DataGen.OPTION2;
import static DataGen.OPTION3;
You could also create an inner class that contains the options:
package staticimport;
import java.util.Random;
public class DataGen {
public class Options {
public static final int OPTION1 = 1;
public static final int OPTION2 = 2;
public static final int OPTION3 = 4;
}
private static Random gen = new Random();
public static String generateString(int n, int options) // <-------
{
if (options == Options.OPTION1)
{
//...
}
else if (options == (Options.OPTION1 | Options.OPTION3))
{
//...
}
//...
return null;
}
}
package staticimport;
import static staticimport.DataGen.Options.*;
public class Tester {
public static void main(String[] args) {
String k = DataGen.generateString(5, OPTION1 | OPTION2);
}
}
Unfortunately, this requires DataGen
to be in a package. It does, however, provide an advantage: it doesn't static import all of DataGen
.