草庐IT

Java 编译器 : How can two methods with the same name and different signatures match a method call?

coder 2024-03-03 原文

我有一个名为 Container 的类:

public class Container {

    private final Map<String, Object> map = new HashMap<>();

    public void put(String name, Object value) {
        map.put(name, value);
    }

    public Container with(String name, Object value) {
        put(name, value);
        return this;
    }

    public Object get(String name) {
        return map.get(name);
    }

    public <R> R get(String name, Function<Object, R> mapper) {

        Object value = get(name);

        if (null == value) {
            return null;
        }

        return mapper
            .apply(value);
    }

    public <R> R get(String name, Class<R> type) {

        Object value = get(name);

        if (null == value) {
            return null;
        }

        if (type.isAssignableFrom(value.getClass())) {
            return type
                .cast(value);
        }

        throw new ClassCastException(String
            .format("%s -> %s", value.getClass(), type));
    }
}

和名为 Token 的类:

public class Token {

    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Token withValue(String value) {
        setValue(value);
        return this;
    }
}

最后是 Token 类的测试类

public class TokenTest {

    @Test
    public void verifyToken() {
        verify("bar", new Token()
            .withValue("bar"));
    }

    @Test
    public void verifyContainer() {
        Container tokens = new Container()
            .with("foo", "bar")
            .with("baz", "bat");

        verify("bar", tokens.get("foo", String.class));
        verify("bat", tokens.get("baz", String::valueOf));  // line 21
    }

    private void verify(String expected, String actual) {
        verify(expected, new Token()
            .withValue(actual));
    }

    private void verify(String expected, Token actual) {
        Assert
            .assertEquals(expected, actual.getValue());
    }
}

测试在 eclipse 中编译和运行得很好。

在命令行上构建时

mvn clean test

出现编译错误:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:testCompile (default-testCompile) on project ambiguous: Compilation failure
[ERROR] /C:/data/projects/java/ambiguous/src/test/java/ambiguous/TokenTest.java:[21,9] reference to verify is ambiguous
[ERROR]   both method verify(java.lang.String,java.lang.String) in ambiguous.TokenTest and method verify(java.lang.String,ambiguous.Token) in ambiguous.TokenTest match

当我将 21 行更改为其中之一时,编译也失败了

verify("bat", tokens.get("baz", e -> String.valueOf(e)));
verify("bat", tokens.get("baz", e -> e.toString));

当我将行更改为其中之一时

verify("bat", tokens.get("baz", String.class));
verify("bat", tokens.get("baz", Object::toString));

编译成功

我不明白为什么会出现这个编译错误。

我发现了以下链接 boxing and unboxing , multiple generic types and intersection types还有这个eclipse compiler bug但我仍然无法理解上述原因。

我的问题是,当映射器 String::valueOf 传递给 get 时,是什么让编译器认为 verify 方法的两个签名匹配 方法?

为了编译,使用了以下 jdk(使用 maven 和 gradle):

$ java -version
openjdk version "1.8.0_201-1-ojdkbuild"
OpenJDK Runtime Environment (build 1.8.0_201-1-ojdkbuild-b09)
OpenJDK 64-Bit Server VM (build 25.201-b09, mixed mode)

最佳答案

根据JLS §15.12.2.2 :

An argument expression is considered pertinent to applicability for a potentially applicable method m unless it has one of the following forms:

  • An implicitly typed lambda expression1.
  • An inexact method reference expression2.
  • [...]

因此:

verify("bar", tokens.get("foo", e -> String.valueOf(e)));

隐式类型的 lambda 表达式 e -> String.valueOf(e) 在重载解析期间从适用性检查中跳过 - verify(...) 方法都变成适用 - 因此存在歧义。

相比之下,这里有一些可行的示例,因为类型是明确指定的:

verify("bar", tokens.get("foo", (Function<Object, String>) e -> String.valueOf(e)));

verify("bar", tokens.get("foo", (Function<Object, String>) String::valueOf));

1 - 隐式类型的 lambda 表达式是一个 lambda 表达式,其中推断出其所有形式参数的类型。
2 - 一个不精确的方法引用 - 具有多个重载。

关于Java 编译器 : How can two methods with the same name and different signatures match a method call?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56294817/

有关Java 编译器 : How can two methods with the same name and different signatures match a method call?的更多相关文章

随机推荐