given this code in Java:
import java.util.function.Consumer;
import java.util.function.Function;
public class Main {
int element;
public Main subclass;
public static void main(String[] args)
{
Main m1 = new Main(3);
Main m2 = new Main(0);
m1.subclass = m2;
m1.foo(Main::getElement, m1::setElement1);
m1.foo(Main::getElement, m1::setElement2);
}
Main(int element)
{
this.element = element;
}
public int getElement()
{
return this.element;
}
public void setElement1(int n)
{
this.element = n;
}
public void setElement2(int n)
{
this.element = 2*n;
}
public void foo(Function<Main, Integer> resourceGetter, Consumer<Integer> resourceSetter)
{
resourceSetter.accept(5);
System.out.println(resourceGetter.apply(this));
if(subclass != null)
this.subclass.foo(resourceGetter, resourceSetter);
}
}
Let's focus on the main and, specifically, on the two method calls: m1.foo(Main::getElement, m1::setElement1) and m1.foo(Main::getElement, m1::setElement2). In the first case, when the program reaches the line: this.subclass.foo(resourceGetter, resourceSetter), the foo method is called in the subclass using the method m1.setElement1 and in the second one, using the method m1.setElement2. Imagine that we would want to call the same method but with an instance of subclass, so that in the first case we would be calling foo with this.subclass.setElement1 and in the second scenario, with this.subclass.setElement2.
Given the fact that the functions should remain public (static option would not be a solution for this), is there any way of inserting the setter as a parameter so that subclass can call its own setter?
I thought about an ugly and non-extensible way that is basically doing a enum of all functions that can be used as a parameter of foo function and passing that enum value as a parameter to the foo function so that it knows which functions to call each time.