Jac*_* G. 3 java import var type-inference java-10
假设我有以下类定义单个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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我可以创建一个Utility使用此方法的类(位于相同的包中):
public class Test {
public static void main(String[] args) throws Exception {
var channel = Utility.getChannel();
System.out.println(channel);
channel.close();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,Test似乎不需要任何import语句,即使它AsynchronousSocketChannel在本地使用.如果我要输入AsynchronousSocketChannel channel = ...;,那么显然需要import语句.
我的假设是在编译时推断导入语句(当利用本地类型推断时)是正确的吗?
SLa*_*aks 12
import语句是纯粹的语法结构; 它们只允许您在不编写完整包名的情况下引用类型名称.
特别是,它们与装载任何东西无关.
如果您从未在代码中明确使用typename,则不需要导入.