3

假设我有以下定义单个static实用程序方法的类:

import java.io.IOException;
import java.nio.channels.AsynchronousSocketChannel;

public class Utility {
    public static AsynchronousSocketChannel getChannel() {
        try {
            return AsynchronousSocketChannel.open();
        } catch (IOException e) {
            throw new IllegalStateException();
        }
    }
}

然后,我可以创建一个使用此方法的类(位于与 相同的包中Utility):

public class Test {
    public static void main(String[] args) throws Exception {
        var channel = Utility.getChannel();
        System.out.println(channel);
        channel.close();
    }
}

但是,Test似乎不需要任何导入语句,即使它AsynchronousSocketChannel在本地使用。如果我改为键入AsynchronousSocketChannel channel = ...;,那么显然需要导入语句。

我的假设是在编译时(利用本地类型推断时)推断出import 语句是否正确?

4

1 回答 1

12

import语句是纯粹的句法结构;它们只允许您引用类型名而不写其完整的包名。

特别是,它们与加载任何东西无关。

如果您从未在代码中明确使用类型名,则不需要导入。

于 2018-05-07T18:16:03.037 回答