本地类型推断是否不需要某些导入语句?
Are some import statements not required with local type inference?
假设我有以下 class 定义了一个 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();
}
}
}
然后我可以创建一个 class(位于与 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
语句是一个纯粹的语法结构;他们只允许您引用类型名称而不用写完整的包名称。
特别是,它们与加载任何内容无关。
如果您从未在代码中显式使用类型名称,则不需要导入。
假设我有以下 class 定义了一个 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();
}
}
}
然后我可以创建一个 class(位于与 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
语句是一个纯粹的语法结构;他们只允许您引用类型名称而不用写完整的包名称。
特别是,它们与加载任何内容无关。
如果您从未在代码中显式使用类型名称,则不需要导入。