首页 > 解决方案 > 本地类型推断不需要一些导入语句吗?

问题描述

假设我有以下定义单个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 语句是否正确?

标签: javaimportvartype-inferencejava-10

解决方案


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

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

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


推荐阅读