简体   繁体   中英

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. 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

Update

Updating to clarify that I'm using Springboot. Foo is a bean. The method in questions uses some other injected values, which is why it can't be 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

You either have to provide an instance of Foo or make method doAction() to be static , otherwise you can't access it. 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).
  • Add a static modifier to the declaration of doAction() .

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);
        
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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