事情是这样的,我在查看Java的Optional
类,并注意到在public static<T> Optional<T> empty()
文档中有以下内容:
@param <T> The type of the non-existent value*.
在查看整个类并搜索这里和其他一些页面之后,我遇到了这个问题,我无法回答:
- 一个空的
Optional
可以有特定的类型吗? 1.1 如果可以,如何设置它? 1.2 是否有任何方法检查其类型?
事情是这样的,我在查看Java的Optional
类,并注意到在public static<T> Optional<T> empty()
文档中有以下内容:
@param <T> The type of the non-existent value*.
在查看整个类并搜索这里和其他一些页面之后,我遇到了这个问题,我无法回答:
Optional
可以有特定的类型吗?
1.1 如果可以,如何设置它?
1.2 是否有任何方法检查其类型?它是您指定的任何类型:
// Empty Optional with value type String
Optional<String> opt = Optional.empty();
这是来自于 OpenJDK 11 的该方法的源代码:
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
EMPTY
是一个静态实例(源代码链接如上):
/**
* Common instance for {@code empty()}.
*/
private static final Optional<?> EMPTY = new Optional<>();
Optional
类是一个可能包含特定元素的容器。因此,它具有两个概念:
它可能包含的类型是通过泛型指定的。泛型只存在于编译时期,并在运行时丢失。
回答您的问题:
Optional
时,通常定义它可能包含某种类型,如下所示:Optional<String> optionalString;
此时我们知道optionalString
可能会包含一个字符串。如果我们这样做:
Optional<String> optionalString = Optional.empty();
它实际上并不包含任何内容,但我们可以在任何需要Optional<String>
的地方使用它。
Optional
类型会根据其使用进行推断。就像上面一样,您可以指定Optional.empty()
为Optional<String>
。您也可以通过方法的返回值来指定其类型,如下所示:public Optional<Integer> findNumber() {
return Optional.empty();
}
Optional
没有类型。Optional.of(urObject)
,现在“类型”是Optional。
3. 您不能检查Optional的类型。
Optional
。当您需要一个空的Optional<T>
时,编译器可以假定上下文所需的任何泛型类型T
;这不会导致问题,因为其中没有对象是错误类型。 - khelwood(T) null
一样模糊(尽管不是null)。empty()
是一个函数而不是类常量的原因是你可以有一个带类型的Optional<T>
值。 - Joop EggenList<String> list1 = Collections.emptyList(); List<Integer> list2 = Collections.emptyList();
没有任何不同,列表的类型仅由它们的引用变量决定。因此,或许令人惊讶的是,list1 == (Object)list2
将为true
。对于Function<String,String> f1 = Function.identity(); Function<Integer,Integer> f2 = Function.identity();
也是一样的。 - Holger