java - 从 Java 中的静态表中指向实例方法
问题描述
我想要一个像这样的表:
static final Record [] table = {
new Record( Pattern.compile( "regex1" ), MyClass::f1 ),
new Record( Pattern.compile( "regex2" ), MyClass::f2 )
};
wheref1
等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
我想通了 staticf1
等f2
,但是无论我尝试什么等的非静态声明,我都会收到各种相当难以理解的错误消息f1
。我认为可以做到吗?
解决方案
您可以使用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)
.
推荐阅读
- python - 如何从不同的电脑安装 Python 项目 requirements.txt?
- python - django中的值错误指的是什么,我被卡住了
- javascript - 如何在 Shopify 私有 APP 中发出 API 请求
- javascript - 从 Firebase 存储中获取 URL 照片时,等待新的 Promise 不起作用
- python - 存储在 mongoDB 中的 Django 'Dynamic' 对象
- react-native - 关于 react-native 中的 Svg 行,我可以将 x1、y1 设置为变量吗?
- uber-api - Uber Eats api 与餐厅经理应用程序的集成
- python - 如何使用 NLP 从评论中提取颜色?
- git - 将新代码库推送到现有仓库的分支
- c# - 只有赋值调用递增递减等待和新对象表达式可以作为语句 Unity Pong Game