java - 本地类型推断不需要一些导入语句吗?
问题描述
假设我有以下定义单个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 语句是否正确?
解决方案
import
语句是纯粹的句法结构;它们只允许您引用类型名而不写其完整的包名。
特别是,它们与加载任何东西无关。
如果您从未在代码中明确使用类型名,则不需要导入。
推荐阅读
- r - svd(X) 中的错误:“x”中的值无限或缺失
- indy - Lazarus RingCentral API RingOut TIdHTTP 中的 Indy 10
- node.js - 在 react-native 中上传 blob/文件,内容为空
- arrays - 在 xslt 1.0 中格式化值数组
- javascript - 如何从 javascript 代码向使用 socket.io 连接的所有用户发出结果
- javascript - Firestore 删除用户的所有引用
- c++ - 字符串文字不会有正则表达式的结尾
- reactjs - localStorage 保存未更新的状态,即使它在 setState 之后
- python - 除了语句不会返回到 For 循环 Python tweepy
- atom-editor - atom-helper:哪个包可以防止 100% 的 CPU 使用?