简体   繁体   中英

How to reference non-static methods in a static context (to call them on an instance for method serialisation)

Now I have a class in one of my java programs that defines a series of non-static consumers that do different things:

public class Foo {
    //pretend these methods have bodies
    public void addWood(String s) ... 
    public void addMetal(String s) ...
    public void addFish(String s) ...
    public void addFood(String s) ...

    public void process() {}
}

As well as a "process" method that will call these functions.

However I want the exact functions and order that these functions are called to be stored in some static state of the class, so the idea I had for this was simple at first:

I simply create a HashMap<Parameter,Method> (the parameters are always unique as they're supplier objects). And then In some external function, when I want to add a function to be called by an instance of Foo I simply do something like this in an external function:

Foo.hash_map.put( parameter, Foo::addWood );

However I can't do this as addWood isn't static, so how do I do this, how do I reference a non-static method, statically, to be called non-statically, if that makes any sense

Now I know this probably reeks of abstraction issues but I'm working with an external codebase so this is kind of the best I can do in terms of getting the program to do what I want. I can't see any underlying reason something like this wouldn't work and I admit it's a slightly odd thing to want to do but it would be very helpful if anyone knows an easy way to do it.

Foo::addWood works just peachy fine. It would fit any FunctionalInterface that takes in an instance of Foo as well as a String and returns nothing:

private final Map<String, BiConsumer<Foo, String>>;

would do the job.

I'm not sure, however, if this is the best 'fit'; I'd instead make a List<> of Consumer :

List<Consumer<Foo>> list = ..;
list.add(foo -> foo.addWood("Hello"));
list.add(foo -> foo.addMetal("Goodbye"));

...


Foo foo = ...;
for (var consumer : list) list.accept(foo);

At least, if as you say the string parameter is always constant.

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