首页 > 解决方案 > NoSuchMethodError 而不是调用正确的方法

问题描述

我遇到了一个奇怪的行为。以下代码:

private void setSegments(Set<Long> segments) {
    this.segments = ImmutableSet.copyOf(segments);
}

投掷

java.lang.NoSuchMethodError: com.google.common.collect.ImmutableSet.copyOf(Ljava/util/Collection;)Lcom/google/common/collect/ImmutableSet;

我通过在方法中添加以下片段来通过反射检查类内容:

try {
    Class c = ImmutableSet.class;
    Method[] m = c.getDeclaredMethods();
    for (int i = 0; i < m.length; i++) {
        LOGGER.error("method: " + m[i].toString());
    }
} catch (Throwable e) {
    System.err.println(e);
}

其中,在所有其他方法中,打印出来

Segments:method: public static com.google.common.collect.ImmutableSet com.google.common.collect.ImmutableSet.copyOf(java.util.Iterator)
Segments:method: public static com.google.common.collect.ImmutableSet com.google.common.collect.ImmutableSet.copyOf(java.lang.Iterable)

我不明白为什么不调用带有 Iterable 参数的方法。毕竟,Set 扩展了实现 Iterable 的 Collection。

感谢您的任何想法

标签: javaoverridingnosuchmethoderror

解决方案


推荐阅读