简体   繁体   English

通过签名推断的Java 8方法参考解析,这是坏的吗?

[英]Java 8 method reference resolution by signature inference, is this broken?

A class implements a functional interface. 一个类实现一个功能接口。 This class has multiple methods with similar signatures, ie. 此类具有多种具有相似签名的方法,即。 they have an empty parameter list. 他们有一个空的参数列表。 A method that accepts this functional interface as an argument will accept any of those methods, even though they are not defined in the interface. 接受此功能接口作为参数的方法将接受任何这些方法,即使它们未在接口中定义。

public class Frogs {
    public static void main(String[] args) {
        Froggo frog = new Froggo();
        moveTheFrog(frog::move);
        moveTheFrog(frog::jump);
        moveTheFrog(frog::swim);
        moveTheFrog(frog::croak);
        }
    static void moveTheFrog(Froginetic froginetic) {
        froginetic.move();
        }
    @FunctionalInterface
    interface Froginetic {
        void move();
        }
    static class Froggo implements Froginetic {
        @Override
        public void move() { System.out.println("move"); }
        void swim() { System.out.println("swim"); }
        void jump() { System.out.println("jump"); }
        void croak() { 
            System.out.println("croak"); 
            System.exit(2460); // bucks}
            }
        }
    }

Can't the compiler see that frog::jump is not defined in Froginetics? 编译器看不到Froginetics中未定义frog :: jump吗? The designer of the moveTheFrog method would definitely not expect, nor account for, the effects of frog::croak. moveTheFrog方法的设计者绝对不会想到也不考虑frog :: croak的影响。

It looks like good old fashioned C function ptrs are now a part of Java. 看起来不错的老式C函数ptrs现在已成为Java的一部分。

Is this broke? 这坏了吗? Or is this by design? 还是这是设计使然?

As we know from the Java tutorials 从Java教程中我们知道

moveTheFrog(frog::move);

is more or less equivalent to 或多或少等于

moveTheFrog(() -> from.move());

Because the target type of the argument is a functional interface, the body of the lambda expression becomes the body of the interface method. 因为参数的目标类型是函数接口,所以lambda表达式的主体成为接口方法的主体。 Similarly for method references, the body of the interface method becomes the body of the referenced method. 同样,对于方法引用,接口方法的主体成为引用方法的主体。

This is a feature of the language and doesn't have anything to do with the method being defined in one class or another. 这是语言的功能,与在一个或另一个类中定义的方法没有任何关系。 It's about compatibility between method signatures. 关于方法签名之间的兼容性。

Froginetic doesn't know anything about Froggo . FrogineticFroggo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM