我想要一张这样的桌子:
static final Record [] table = {
new Record( Pattern.compile( "regex1" ), MyClass::f1 ),
new Record( Pattern.compile( "regex2" ), MyClass::f2 )
};其中,f1、f2等是对实例(而非静态)方法的引用,其中包含参数和返回值,每个方法如下所示:
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?我想出了静态f1、f2等,但是我得到了各种各样令人费解的错误消息,不管我尝试了什么非静态的f1声明等等。我假设这是可以做到的?
发布于 2021-08-25 23:00:36
您需要这些函数是static,或者需要解释实例变量将来自何处。为了给您提供一个完整的示例,我不得不编写Record。简而言之,你想要一个Function<Integer, Integer>,你想要apply它。就像,
class Record {
private Pattern regex;
private Function<Integer, Integer> func;
public Record(Pattern p, Function<Integer, Integer> f) {
this.regex = p;
this.func = f;
}
void foo(String s, int arg) {
for (Record r : table) { // this.regex.matcher(s).matches() ?
if (r.regex.matcher(s).matches()) {
int result = r.func.apply(arg);
break;
}
}
}
static final Record[] table = {
new Record(Pattern.compile("regex1"), Record::f1),
new Record(Pattern.compile("regex2"), Record::f2)
};
public static int f1(int arg) {
return arg * arg;
}
public static int f2(int arg) {
return arg + arg;
}
}https://stackoverflow.com/questions/68930670
复制相似问题