简体   繁体   English

如何从枚举构造函数调用 lambda

[英]How to call lambda from Enum constructor

I'm trying to set up a enum where each Enum value has a custom method to be called.我正在尝试设置一个枚举,其中每个枚举值都有一个要调用的自定义方法。 However, it tells me that the method must be static.但是,它告诉我方法必须是 static。 Is there a way to reference a non-static method?有没有办法引用非静态方法?

My code looks like this我的代码看起来像这样

public class Foo {

    private enum MyEnum {
        TGD410(Foo::doAction);

        private MyLambda myLambda;

        MyEnum(MyLambda myLambda) {
            this.myLambda = myLambda;
        }

        public void execute(String str1, String str2) {
            myLambda.apply(str1, str2);

        }
    }

    public void doAction(String str1, String str2) {

    }

    @FunctionalInterface
    public interface MyLambda{
        void apply(String str1, String str2);
    }
}

在此处输入图像描述

Is there some other way to do what I want to do?还有其他方法可以做我想做的事吗? I think I need to pass in a reference to the Foo object, but not sure how to specify that, since this refers to the Enum我想我需要传递对 Foo object 的引用,但不确定如何指定,因为this是指枚举

Update更新

Updating to clarify that I'm using Springboot.更新以澄清我正在使用 Springboot。 Foo is a bean. Foo是一个豆子。 The method in questions uses some other injected values, which is why it can't be static.有问题的方法使用了其他一些注入值,这就是为什么它不能是 static。

I'm considering just not using a Lambda and instead putting my method in another POJO (which implements some common interface), which can be instantiated我正在考虑不使用 Lambda 而是将我的方法放在另一个 POJO(它实现一些通用接口)中,可以实例化

You either have to provide an instance of Foo or make method doAction() to be static , otherwise you can't access it.您必须提供Foo的实例或使方法doAction()成为static ,否则您无法访问它。 Precisely as the error message tells you.正如错误消息告诉你的那样。

So you have two options:所以你有两个选择:

  • Provide an instance (for instance via constructor of enum), which judging by the signature of doAction() seem to be unnecessary because there's nothing that points that this method depends somehow on the state of Foo instance (unless you're not going to use some properties of Foo in the body of the method which is omited).提供一个实例(例如通过枚举的构造函数),从doAction()的签名判断似乎是不必要的,因为没有任何迹象表明该方法在某种程度上依赖于Foo实例的 state (除非你不打算使用Foo在方法体中的一些属性被省略)。
  • Add a static modifier to the declaration of doAction() .doAction()的声明中添加static修饰符。

The later fix is trivial, here's a way to apply the first one:后面的修复是微不足道的,这是应用第一个的方法:

private enum MyEnum {
    TGD410(new Foo()); // instance of Foo is provided while initializing enum-member
    
    private MyLambda myLambda;
    
    MyEnum(Foo foo) {
        this.myLambda = foo::doAction;
    }
    
    public void execute(String str1, String str2) {
        myLambda.apply(str1, str2);
        
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM