1

A class has a reference to another instance (autowired via Spring)

public class Instance1 {
    public void m1(String args) {
        System.out.println(arg);
    }
    public void m2(String args) {
        System.out.println(arg);
    }
    public void m3(String args) {
        System.out.println(arg);
    }
}

public class process() {

@AutoWire
    public Instance1 instance1

    public void processA() {
        // Get a reference to m1, m2, or m3
        processB(<pass referrnce here>);
    }
    public void processB(<accept reference to m1, m2 , m3 here>) {
        // Call either m1, m2, or m3
    }
}

That instance includes 3 methods, let's say m1, m2 and m3. I want to be able to set a reference to each of those methods and pass it as a parameter to another local method, which will call either m1, m2 and m3.

Monolith
  • 1,067
  • 1
  • 13
  • 29
javaCoder
  • 37
  • 5
  • 2
    Possible duplicate of [Java Pass Method as Parameter](https://stackoverflow.com/questions/2186931/java-pass-method-as-parameter) – rghome Mar 13 '19 at 16:46
  • Could you explain why you want to/have to do it this way? It sounds like a case for polymorphism or lambdas. – Liam Mar 13 '19 at 19:05

1 Answers1

0

You can create Consumer for each method:

public void processA() {
    processB(instance1::m1, instance1::m2, instance1::m3);
}

public void processB(Consumer<String> c1, Consumer<String> c2, Consumer<String> c3) {
    c1.accept("Arg");
    c2.accept("Arg");
    c3.accept("Arg");
}
Ruslan
  • 6,090
  • 1
  • 21
  • 36
  • Thank you Ruslan, Let me give this a try; I'll let you know on Tuesday! – javaCoder Mar 17 '19 at 04:58
  • Instantiated an instance of Instance1 in static main and it worked: Instance1 instance1 = new Instance1(); processB(instance1::m1, instance1::m2, instance1::m3); – javaCoder Mar 18 '19 at 19:42