Java 8中的模糊方法,为什么? [英] Ambiguous method in Java 8, why?

查看:551
本文介绍了Java 8中的模糊方法,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public static void main(String ... args){
then(bar()); //编译错误
}

public static< E extends Exception> E bar(){
return null;
}

public static void then(Throwable actual){}

public static void then(CharSequence actual){}
javac Ambiguous.java

$ b
$ b

  Ambiguous.java:4:error:then to be ambiguous 
then(bar());
^
both方法then(Throwable)in Ambiguous and method then(CharSequence)in Ambiguous match
1 error

为什么这种方法不明确?此代码在Java 7下成功编译!



将方法栏更改为:

  public static< E extends Float> E bar(){
return null;
}

此编译没有任何问题,但在IntelliJ Idea中报告为错误解决方法 then(java.lang.FLoat))。



此代码在Java 7下失败 - javac -source 1.7 Ambiguous.java

  Ambiguous.java:4:error: (Float)
then(bar());
$
方法Ambiguous.then(Throwable)不适用
(参数不匹配; Float不能转换为Throwable)
方法Ambiguous.then(CharSequence)不适用
(参数不匹配; Float不能转换为CharSequence)
1错误

Java版本

  Java版本1.8.0_40
Java™SE运行时环境(build 1.8.0_40-b25)
Java HotSpot™64位服务器虚拟机(build 25.40-b25,混合模式)


  public class Foo extends Exception implements CharSequence {
// ...
}

Foo 实现 Throwable CharSequence 。因此,如果为此实例设置 E ,则Java编译器不知道要调用哪个方法。



原因可能没有问题,因为Java7 是泛型不太实现。如果你自己没有提供 E (比如(Foo)bar()),Java会回退在 E 这是的基本概念中实现了Exception E 因此只被认为是 Exception 的一个实例。



Java8 type inference 已改进,现在 E 的类型为从 then()调用的参数派生,换句话说编译器首先查找可能的类型 then()需要,问题是他们都是有效的选择。所以在这种情况下,它变得模糊不清。






概念证明



现在我们稍微修改您的代码并显示解决模糊调用的方式: 假设我们将代码修改为:

  public class Main {
public static void main(String ... args){
then(bar() ); //编译错误
}
public static< E extends Exception> E bar(){
return null;
}
public static void then(CharSequence actual){
System.out.println(char);




$ b

如果你在 Java8 (它打印 char ),因为Java8只是假设有这样的类 Foo (它为它创建了某种内部类型)。



Java7 中运行它会产生问题:

  /MyClass.java:18:error:method然后在类MyClass中不能应用于给定的类型; 
then(bar()); //编译错误
^
required:CharSequence
found:Exception
reason:actual argument异常无法通过方法调用转换转换为CharSequence
1错误

它对 Exception 做了一个回退,并且找不到



如果您在 Java8 中运行原始代码,那么会因为模糊的调用而出错,如果您在 Java7 中运行它,但它将使用 Throwable 方法。




总之:编译器旨在猜测Java8中的 E ,而在Java7中,最保守的类型是拾取。


public static void main(String... args){
    then(bar()); // Compilation Error
}

public static <E extends Exception> E bar() {
    return null;
}

public static void then(Throwable actual) { }

public static void then(CharSequence actual) { }

Compilation result (from command line javac Ambiguous.java)

Ambiguous.java:4: error: reference to then is ambiguous
        then(bar());
        ^
  both method then(Throwable) in Ambiguous and method then(CharSequence) in Ambiguous match
1 error

Why this method is ambiguous? This code compile with success under Java 7!

After changing method bar to:

public static <E extends Float> E bar() {
    return null;
}

This compiles without any problems, but is reported as error in IntelliJ Idea (Cannot resolve method then(java.lang.FLoat)).

This code fails under Java 7 - javac -source 1.7 Ambiguous.java:

Ambiguous.java:4: error: no suitable method found for then(Float)
        then(bar());
        ^
    method Ambiguous.then(Throwable) is not applicable
      (argument mismatch; Float cannot be converted to Throwable)
    method Ambiguous.then(CharSequence) is not applicable
      (argument mismatch; Float cannot be converted to CharSequence)
1 error

Java version

java version "1.8.0_40"
Java(TM) SE Runtime Environment (build 1.8.0_40-b25)
Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)

解决方案

Consider the following class:

public class Foo extends Exception implements CharSequence {
    //...
}

The class Foo implements both Throwable and CharSequence. So in case E is set to this instance, the Java compiler does not know which method to call.

The reason there is probably no problem for Java7 is that generics are less implemented. In case you don't provide an E yourself (e.g. (Foo) bar()), Java will fall back on the basic verion of E which is implements Exception, E is thus only considered to be an instance of Exception.

In Java8, the type inference is improved, the type of E is now derived from the parameter called for by then(), in other words the compiler first looks what possible types then() needs, the problem is that they both are valid choices. So in that case it becomes ambiguous.


Proof of concept:

Now we will slightly modify your code and show how ambiguous calls are resolved:

Say we modify the code to:

public class Main {
    public static void main(String... args){
        then(bar()); // Compilation Error
    }
    public static <E extends Exception> E bar() {
        return null;
    }
    public static void then(CharSequence actual) {
        System.out.println("char");
    }
}

If you run this in Java8, there is no problem (it prints char), because Java8 simply assumes there is such class Foo (it created some kind of "inner" type for it that derived from both).

Running this in Java7 yields problems:

/MyClass.java:18: error: method then in class MyClass cannot be applied to given types;
    then(bar()); // Compilation Error
    ^
  required: CharSequence
  found: Exception
  reason: actual argument Exception cannot be converted to CharSequence by method invocation conversion
1 error

It did a fallback on Exception and couldn't find a type that could deal with it.

If you run the original code in Java8, it will error because of the ambiguous call, if you run it in Java7 however, it will use the Throwable method.


In short: the compiler aims to "guess" what E is in Java8, whereas in Java7 the most conservative type was picked.

这篇关于Java 8中的模糊方法,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆