【问题标题】:How to specify the right type for ReferenceQueue.remove() in Java?如何在 Java 中为 ReferenceQueue.remove() 指定正确的类型?
【发布时间】:2013-06-08 02:18:33
【问题描述】:

我有一堂课,ReferenceQueueWeakReferences。

class Example<K,V>
{
    ReferenceQueue<WeakReference<V>> queue = null;
    Thread cleanup = null;
[...]
    Example () {
        queue = new ReferenceQueue<WeakReference<V>>();
        cleanup = new Thread() {
                public void run() {
                    try {
                        for (;;) {
                            WeakReference<V> ref = queue.remove();
[...]

但是当我尝试编译这个时,我得到一个“不兼容的类型”错误:

found   : java.lang.ref.Reference<capture#189 of ? extends java.lang.ref.WeakReference<V>>
required: java.lang.ref.WeakReference<V>
                            WeakReference<V> ref = queue.remove();
                                                               ^

我不明白这一点,因为我已将引用队列定义为 V 的弱引用队列,因此我期望 V 的弱引用是 remove() 的结果。

这是错的吗?我该如何解决这个问题?

我也尝试将Reference&lt;V&gt; 作为remove() 的返回值,但这无济于事。我尝试了强制转换结果,但这只会将错误变成警告。

【问题讨论】:

    标签: java weak-references


    【解决方案1】:

    您应该使用ReferenceQueue&lt;V&gt;,而不是ReferenceQueue&lt;WeakReference&lt;V&gt;&gt;。您需要将从队列中拉出的引用显式转换为 WeakReference&lt;V&gt;

    【讨论】:

    • 在不产生“未经检查的演员表”警告的情况下,有没有办法获得正确的类型?
    • 好的。我添加了@SuppressWarnings。我的example 似乎有效。
    猜你喜欢
    • 2019-12-22
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 2021-04-01
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多