问题
I was asking my self while coding in Java, does the import static com.example.method
is a good the to do or is it better to import the whole class.
回答1:
Depends on the context, not exist an explicit rule to use in all the cases. But the most common use is when you do a test and need to import classes like Assert.* or Mockito.*, in order to no-repeat Assertion.assertEquals a lot of times a good idea is to do something like this:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ErrorsControllerImplTest {
@Test
void should_return_all_the_errors_types() {
ErrorsController controller = new ErrorsControllerImpl();
assertAll(
() -> assertEquals(58, controller.getAllErrors().size()),
() -> assertEquals("BadRequestStatus {code=4000509, message='Site must have a value'}",
controller.getAllErrors().get(0)));
}
}
As another user said, the idea is that the code will be readable and remove duplicates parts.
回答2:
It's a mehh... feature, to be sincere.
import static java.util.List.*;
import static java.lang.String.*;
import static java.lang.Math.*;
...
of(1); //of 1...wat
valueOf(mother); //really..
random(); //i'm scared
valueOf(E);
The only real useful scenario would be when you need to constantly use constants from other class. Such as in the example above, if the class was some kind of specific MathUtils
class for your project that must call Math
's methods in almost all of its code.
Or as in the top answer's scenario, when running test classes such as Mockito
.
来源:https://stackoverflow.com/questions/65452714/is-import-static-a-good-practice