为什么谓词< ;?超级SomeClass>不适用于对象? [英] Why is Predicate<? super SomeClass> not applicable to Object?
问题描述
假设我们有一个谓词为Predicate<? super SomeClass>
的谓词.我天真地希望它适用于层次结构中所有SomeClass
的超类,包括Object
.
Assume we have a predicate declared as Predicate<? super SomeClass>
. I would naively expect it to be applicable to any superclass of SomeClass
up the hierarchy, including Object
.
但是,该谓词不适用于Object
.我收到以下错误:
However this predicate is not applicable to Object
. I get the following error:
谓词类型的方法test(capture#3-of Some SomeClass的方法)不适用于参数(Object)
The method test(capture#3-of ? super SomeClass) in the type Predicate is not applicable for the arguments (Object)
演示.
为什么Predicate<? super SomeClass>
不适用于Object
的实例?
Why is Predicate<? super SomeClass>
not applicable to an instance of Object
?
代码:
import java.util.*;
import java.lang.*;
import java.io.*;
import java.net.URL;
import java.util.function.Predicate;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Predicate<? super URL> p = u -> u.getFile().isEmpty();
p.test(new Object());
}
}
推荐答案
对于Predicate<? super SomeClass>
变量,您可以分配Predicate<SomeClass>
实例或Predicate<Object>
实例.
For a Predicate<? super SomeClass>
variable, you can assign a Predicate<SomeClass>
instance, or a Predicate<Object>
instance.
但是,您不能将Object
传递给Predicate<SomeClass>
的test()
方法.您只能传递SomeClass
实例.
However, you can't pass an Object
to the test()
method of a Predicate<SomeClass>
. You can only pass a SomeClass
instance.
因此,您不能将Object
传递给Predicate<? super SomeClass>
Therefore you can't pass an Object
to the test()
method of a Predicate<? super SomeClass>
请考虑以下内容:
Predicate<URL> p1 = u -> u.getFile().isEmpty();
Predicate<? super URL> p2 = p1;
p2
指的是Predicate<URL>
,因此您不能将new Object()
传递给其test()
方法.
p2
is referring to a Predicate<URL>
, so you can't pass a new Object()
to its test()
method.
换句话说,为了使p.test(new Object())
被编译器接受,它对于可分配给Predicate<? super URL> p
变量的任何 Predicate
必须有效.由于可以将Predicate<URL>
Predicate
分配给该变量,并且其test()
方法无法接受Object
,因此编译器无法接受p.test(new Object())
.
In other words, in order for p.test(new Object())
to be accepted by the compiler, it must be valid for any Predicate
that can be assigned to the Predicate<? super URL> p
variable. Since the Predicate<URL>
Predicate
can be assigned to that variable, and its test()
method cannot accept an Object
, p.test(new Object())
cannot be accepted by the compiler.
顺便说一句,在您的特定示例中,您正在创建Predicate<URL>
,而URL
是最终课程.因此,您只需将其声明为:
BTW, in your specific example, you are creating a Predicate<URL>
, and URL
is a final class. Therefore, you should simply declare it as:
Predicate<URL> p = u -> u.getFile().isEmpty();
没有理由使用? super
或? extends
.
这篇关于为什么谓词< ;?超级SomeClass>不适用于对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!