我想要一个静态映射,其中的值是实例方法。像这样的东西:
public class MyClass {
static Map<MyEnum, Consumer<String>> methodMapping;
static {
methodMapping = new EnumMap<>(MyEnum.class);
methodMapping.put(MyEnum.FIRST, MyClass::firstMethod);
methodMapping.put(MyEnum.SECOND, MyClass::secondMethod);
}
void firstMethod(String param) {
...
}
void secondMethod(String param) {
...
}
}
这给了我一个错误,说“不能从静态上下文引用非静态方法”。我明白为什么如果我尝试从静态上下文调用方法会出现问题,但是是否可以从实例方法从映射中检索方法并将其传递给 this
?喜欢:
MyClass.methodMapping.get(MyEnum.FIRST).accept(this, "string");
最佳答案
这很容易解决,只需将 Consumer
更改为 BiConsumer
,将 MyClass
的接收器实例转换为函数的参数即可:
public class MyClass {
static Map<MyEnum, BiConsumer<MyClass,String>> methodMapping;
static {
methodMapping = new EnumMap<>(MyEnum.class);
methodMapping.put(MyEnum.FIRST, MyClass::firstMethod);
methodMapping.put(MyEnum.SECOND, MyClass::secondMethod);
}
void firstMethod(String param) {
...
}
void secondMethod(String param) {
...
}
void callTheMethod(MyEnum e, String s) {
methodMapping.get(e).accept(this, s);
}
}
关于java - 在静态上下文中存储对实例方法的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42345403/