【问题标题】:Are some import statements not required with local type inference?本地类型推断不需要一些导入语句吗?
【发布时间】:2018-10-17 14:42:06
【问题描述】:

假设我有以下定义单个 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 = ...;,那么显然需要导入语句。

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

【问题讨论】:

    标签: java import var type-inference java-10


    【解决方案1】:

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

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

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

    【讨论】:

    • 不知怎的我忘记了!这是否意味着var channel = Utility.getChannel();java.nio.channels.AsynchronousSocketChannel channel = Utility.getChannel(); 的同义词?
    • @JacobG.:是的;这都是语法糖。
    • 另见“Do Java Lambda Expressions Utilize “Hidden” or Local Package Imports?”,因为使用类型而不通过名称引用它们(因此不需要import 语句)要旧得多......
    • @SLaks 这不是真正的语法糖,它是一种编译推断类型,有些类型由于语言而无法声明,但可以由编译器推断...var test = new Object(){ int x = 3; }; int y = test.x;
    猜你喜欢
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    相关资源
    最近更新 更多