"导入"之后的"静态"修饰符是什么意思?

时间:2020-03-06 15:01:31  来源:igfitidea点击:

像这样使用时:

import static com.showboy.Myclass;

public class Anotherclass{}

import static com.showboy.Myclassimport com.showboy.Myclass有什么区别?

解决方案

请参阅说明文件

The static import declaration is
  analogous to the normal import
  declaration. Where the normal import
  declaration imports classes from
  packages, allowing them to be used
  without package qualification, the
  static import declaration imports
  static members from classes, allowing
  them to be used without class
  qualification.
  
  So when should you use static import?
  Very sparingly! Only use it when you'd
  otherwise be tempted to declare local
  copies of constants, or to abuse
  inheritance (the Constant Interface
  Antipattern). In other words, use it
  when you require frequent access to
  static members from one or two
  classes. If you overuse the static
  import feature, it can make your
  program unreadable and unmaintainable,
  polluting its namespace with all the
  static members you import. Readers of
  your code (including you, a few months
  after you wrote it) will not know
  which class a static member comes
  from. Importing all of the static
  members from a class can be
  particularly harmful to readability;
  if you need only one or two members,
  import them individually. Used
  appropriately, static import can make
  your program more readable, by
  removing the boilerplate of repetition
  of class names.

静态导入用于导入类的静态字段/方法,而不是:

package test;

import org.example.Foo;

class A {

 B b = Foo.B_INSTANCE;

}

你可以写 :

package test;

import static org.example.Foo.B_INSTANCE;

class A {

 B b = B_INSTANCE;

}

如果我们经常在代码中使用另一个类中的常量,并且静态导入不是模棱两可的,这将很有用。

顺便说一句,在示例中," import static org.example.Myclass;"将不起作用:import用于类,import static用于类的静态成员。

我们声明的这两种导入之间没有区别。但是,我们可以使用静态导入来允许无限制地访问其他类的静态成员。我以前必须这样做的地方:

import org.apache.commons.lang.StringUtils;
      .
      .
      .
if (StringUtils.isBlank(aString)) {
      .
      .
      .

我可以做这个:

import static org.apache.commons.lang.StringUtils.isBlank;
      .
      .
      .
if (isBlank(aString)) {
      .
      .
      .

the difference between "import static com.showboy.Myclass" and "import com.showboy.Myclass"?

第一个应该产生编译器错误,因为静态导入仅适用于导入字段或者成员类型。 (假设MyClass不是showboy的内部类或者成员)

我想你是说

import static com.showboy.MyClass.*;

如上所述,这使得MyClass中的所有静态字段和成员都可以在实际的编译单元中使用,而不必限定它们的数量……如上所述