首页 > 解决方案 > 从 Java 中的静态表中指向实例方法

问题描述

我想要一个像这样的表:

static final Record [] table = {
    new Record( Pattern.compile( "regex1" ), MyClass::f1 ),
    new Record( Pattern.compile( "regex2" ), MyClass::f2 )
};

wheref1f2是对带有参数和返回值的实例(非静态)方法的引用,每个方法如下所示:

public int f1( int arg ) {
    return arg * arg;
}
public int f2( int arg ) {
    return arg + arg;
}

所以我可以像这样调用它们(伪代码):

void foo( String s, int arg ) {
    for( Record r : table ) {
        if( r.regex.matcher( s ).matches() ) {
            int result = r.func.invokeOn( this, arg );
            break;
        }
    }
}

声明构造函数的第二个参数(即伪代码中的Record成员变量)的正确方法是什么?func我想通了 staticf1f2,但是无论我尝试什么等的非静态声明,我都会收到各种相当难以理解的错误消息f1。我认为可以做到吗?

标签: javalambda

解决方案


您可以使用BiFunction<MyClass, Integer, Integer>假设MyClass是包含方法的类(或使用接口而不是类)。对没有实例的非静态方法的方法引用(仅给出类),在方法执行时引入了一个表示实例的附加参数(this作为第一个参数。

class Record {
    BiFunction<MyClass, Integer, Integer> func = MyClass::f1;
}

为了

class MyClass {
    public int f1(int arg) {
        return arg * arg;
    }

    int example(Record r, int arg) {
        return r.func.apply(this, arg);
    }
}

1 - 实际上this参数已经在所有实例方法的字节码中(只是不需要声明它。f1方法相当于public int f1(MyClass this, int arg).


推荐阅读