简体   繁体   English

什么是 static 进口,它在 java 中的重要性是什么

[英]What is static imports and what is its importance in java

While reading some java books, I came to know about static imports.在阅读一些 java 书籍时,我开始了解 static 进口。 I have some doubts in my mind.我心中有些疑惑。

  1. What is static imports.什么是static进口。
  2. When and why to use it.何时以及为何使用它。

Explaination with examples will be helpful.举例说明会很有帮助。

One example is JUnit tests 一个例子是JUnit测试

import static org.junit.Assert.assertEquals;
 ...
 assertEquals(x, y);

Imports are typing shortcuts. 导入是键入快捷方式。 A "regular" import is a shortcut down to the class level... “常规”导入是类级别的快捷方式。

import java.util.List 

Let's you just use 我们就用吧

List l;

Instead of 代替

java.util.List l;

A static import is a shortcut down to the method level. 静态导入是方法级别的快捷方式。 The method must be static, since there is no instance to associate with it... 该方法必须是静态的,因为没有实例与之关联...

import static java.lang.Math.abs

Lets you just use 让你只用

x = abs(y);

instead of 代替

x = java.lang.Math.abs(y);

Imports do not effect your compiled output or running code in any way. 导入不会以任何方式影响您的编译输出或运行代码。 Once something is compiled there's no way to tell if the original source had imports or not. 一旦编译完成,就无法判断原始源是否已导入。

The static import allows you to import the static elements. 静态导入允许您导入静态元素。 Usually used when the same objects are invoked many times. 通常在多次调用相同对象时使用。 An example : in your code you are usually use the element out of the class java.lang.System , you can import statically the element out simplifying and improving the code :) 例子 :在你的代码通常是使用元素java.lang.System的,可以静态导入元素进行简化和改进的代码:)

import static java.lang.System.out;

public static void main(String[] args){
    out.println("Hello");
    out.println("World");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM