Jon Anderson Jon Anderson - 3 months ago 7
Java Question

Can I get a method reference from within the method's class?

Normally when you want to access the current instance's members, you use the

this
operator. Unfortunately
this
doesn't seem to work with method references.

Let's say I have the following setup:

class ClassA
{
public ClassA(Consumer c)
{
//...
}
}

class ClassB
{
public ClassB()
{
ClassA a = new ClassA(this::method);
}

public void method(Object o)
{
//...
}
}


The code above doesn't compile. What I am trying to do is pass
ClassA
a reference to a member method of a particular instance of
ClassB
from within the constructor of
ClassB
. Can this be done?

Edit



After looking over my code the next morning, I realized my simple flaw, which had nothing to do with the question stated above. Using
this
to make a method reference is perfectly acceptable.

Answer

I just extended your code a little, and it compiles and runs:

public class StackOverflow {
    public static void main(String[] args) {
        ClassB b = new ClassB();
        b.useAWith("hello");
    }

    static class ClassA {
        private final Consumer<Object> c;

        public ClassA(Consumer<Object> c) {
            this.c = c;
        }

        public void useMethodWith(Object  o) {
            c.accept(o);
        }
    }

    static class ClassB {
        private final ClassA a;

        public ClassB() {
            this.a = new ClassA(this::method);
        }

        public void useAWith(Object o){
            a.useMethodWith(o);
        }

        public void method(Object o) {
            System.out.println("classB method called with " + o);
        }
    }
}

I have put ClassA and ClassB as inner classes into a sample StackOverFlow class.

I just added some code to store the method and the class in fields, and a method to call it from main. Hope, it didn't get too complicated.

Comments