方法参考中的类型推断 [英] Type Inference in Method Reference

查看:110
本文介绍了方法参考中的类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近把手放在Java 8上并尝试使用方法参考。
我正在尝试不同类型的方法引用,并且卡在引用特定类型的任意对象的实例方法类型中。

I recently put my hands on Java 8 and tried using Method References. I was trying different kinds of Method references and got stuck in the type "Reference to an Instance Method of an Arbitrary Object of a Particular Type".

String[] arr = {"First", "Second", "Third", "Fourth"};

Arrays.sort(arr, String::compareToIgnoreCase);

这非常有效。但是当我尝试通过其类型引用用户定义类的方法时:

This works perfectly well. But when I try to refer a method of a user defined class through its type :

Demo2[] arr = {a, b};

Arrays.sort(arr, Demo2::compare);

这显示编译时错误为无法从静态上下文引用非静态方法。

This displays compile-time error as "Non-static method cannot be referenced from a static context".

这是Demo2类:

public class Demo2 implements Comparator<Demo2> {
    Integer i;

    Demo2(Integer i1){
        i = i1;
    }

    public Integer getI() {
        return i;
    }

    @Override
    public int compare(Demo2 o1, Demo2 o2) {
        return o1.getI().compareTo(o2.getI());
    }
}


推荐答案

As greg-449指向你,你的代码有一个bug。

As greg-449 pointed to you, your code has a bug.

通过制作方法引用,如 YourObjet :: yourMethod 您对实例的方法进行静态引用。因此,将为每个对象调用该方法,因此签名需要与早期的不同

By making a method reference like YourObjet::yourMethod you make a static reference to the method of the instance. So the method will be called for each object and thus the signature needs to be different than the earlier

将编译的代码将具有以下形式:

A code that will compile will be of the following form :

Demo2[] demos = {a, b};
Arrays.sort(demos, Demo2::compareTo);

public class Demo2 {
    Integer i;

    Demo2(Integer i1){
        i = i1;
    }

    public Integer getI() {
        return i;
    }

    public int compareTo(Demo2 other) {
        return this.getI().compareTo(other.getI());
    }
}

但正如RealSkeptic指出的那样,这不正确实施和对象比较的方式。你应该给Arrays.sort方法一个比较器:

But as RealSkeptic pointed out, this is not the correct way to implement and objet comparison. You should give the Arrays.sort method a comparator instead :

 Arrays.sort(demos, (obj1, obj2) -> obj1.getI().compareTo(obj2.getI()));

这篇关于方法参考中的类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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