4

我只是按照本教程使用WatchServiceAPI。我不知道为什么使用WatchEvent<?>而不是WatchEvent<Path>,如果我使用后者,不需要强制转换,或者还有其他情况WatchService可以用来监视非路径事件

@SuppressWarnings("unchecked")
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
    return (WatchEvent<T>)event;
}

void processEvents() {
    for (; ; ) {
        ...
        //why doesn't the poolEvents() return WatchEvent<Path> 
        for (WatchEvent<?> event: key.pollEvents()) {
            WatchEvent.Kind kind = event.kind();

            ...

            //here he use a static method cast() to SuppressWarnings the unchecked warning
            WatchEvent<Path> ev = cast(event);
        }
    }
}
4

1 回答 1

3

WatchService的 Javadoc说:

文件系统报告事件的速度可能比检索或处理事件的速度更快,并且实现可能对其可能累积的事件数量施加未指定的限制。如果实现故意丢弃事件,那么它会安排键的 pollEvents 方法返回事件类型为 OVERFLOW 的元素。消费者可以使用此事件作为触发器来重新检查对象的状态。

StandardWatchEventKinds.OVERFLOW是类型WatchEvent.Kind<Object>,我相信这就是 pollEvents 需要返回一个 ListWatchEvent<?>而不是WatchEvent<Path>. OVERFLOW 的 Javadoc 还提到:

此事件的上下文是特定于实现的,可能为 null

这就是为什么溢出事件的类型需要是WatchEvent<Object>.

请注意,您链接的教程建议以下内容:

使用 kind 方法检索事件的类型。无论密钥注册了哪些事件,都可能接收到 OVERFLOW 事件。您可以选择处理溢出或忽略它,但您应该对其进行测试。

因此,您应该将以下内容添加到您的代码中(如果您还没有):

if (kind == OVERFLOW) {
    continue;
}
于 2014-06-29T16:55:46.663 回答