什么时候是钻石运算符,什么时候不是?

问题描述

考虑以下两行代码

final List<Path> paths = new ArrayList<>();
final FileVisitor<Path> fv = new SimpleFileVisitor<>();

对我来说,它们看起来非常相似。但是,第二行被 Java 编译器 (1.8) 拒绝,并显示消息“无法推断 SimpleFileVisitor 的类型参数”。

谁能解释一下,有什么问题吗?

解决方法

我不明白你是如何得到错误消息 Cannot infer type arguments 因为你的语法是正确的,除了正如许多人已经说过的那样,类 java.nio.file.SimpleFileVisitor 只有一个构造函数,它是protected

protected SimpleFileVisitor() {
}

这意味着只有此类的子类才能初始化 SimpleFileVisitor 的实例,这就是您的代码无法编译的原因。

我不知道这个类,但是通过快速查看代码,我猜他们只是希望您先扩展它(或使用来自其他地方的已经存在的扩展),然后将它用于FileVisitor 接口。

如果您没有要使用的具体子类并且想要创建自己的 MySimpleFileVisitor

public class MySimpleFileVisitor<T> extends SimpleFileVisitor<T> {
    public MySimpleFileVisitor() {
        super(); //<-- here you have the right to call the protected constructor of SimpleFileVisitor
    }
}

...然后您将能够实例化您的类并使用已经实现的方法,如下所示:

FileVisitor<Path> fv = new MySimpleFileVisitor<>(); //<-- here you will be able to correctly infer parameter type as you do in your List example
fv.visitFile(file,attrs); //<-- here you enter the method implemented inside SimpleFileVisitor