gpt4 book ai didi

java - 为什么 WatchService 使用未绑定(bind)的通配符 WatchEvent 而不是 WatchEvent

转载 作者:搜寻专家 更新时间:2023-11-01 03:05:27 25 4
gpt4 key购买 nike

我刚刚关注了这个 tutorial使用WatchService应用程序接口(interface)。我不知道为什么使用 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);
}
}
}

最佳答案

WatchService 的 Javadoc说:

File systems may report events faster than they can be retrieved or processed and an implementation may impose an unspecified limit on the number of events that it may accumulate. Where an implementation knowingly discards events then it arranges for the key's pollEvents method to return an element with an event type of OVERFLOW. This event can be used by the consumer as a trigger to re-examine the state of the object.

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

The context for this event is implementation specific and may be null

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

请注意,您链接的教程建议如下:

Retrieve the type of event by using the kind method. No matter what events the key has registered for, it is possible to receive an OVERFLOW event. You can choose to handle the overflow or ignore it, but you should test for it.

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

if (kind == OVERFLOW) {
continue;
}

关于java - 为什么 WatchService 使用未绑定(bind)的通配符 WatchEvent<?> 而不是 WatchEvent<Path>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24477601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com