Is it possible to apply instance method reference to a different object that the reference source?

705 views Asked by At

As far as my understanding goes, method references can be used either statically or with wrapped object instance, for example:

public class MethodReferencesExampleTest {

    class Example {
        private String variable;

        public Example(String variable) {
            this.variable = variable;
        }

        public String getVariable() {
            return variable;
        }
    }

    @Test
    public void shouldBeAbleToUseBothClassAndInstanceMethodReference() {
        Example objectUnderTest = new Example("variable");

        useClassMethodReference(Example::getVariable, objectUnderTest);
        useInstanceMethodReference(objectUnderTest::getVariable);
    }

    private <T> void useClassMethodReference(Function<T, String> methodReference, T object) {
        System.out.println("Class reference call result = " + methodReference.apply(object));
    }

    private void useInstanceMethodReference(Supplier<String> methodReference) {
        System.out.println("Instance reference call result = " + methodReference.get());
    }

}

What I would like to do is extract instance method reference and somehow convert it to class method reference, so that I could apply it to a different object of the same class, like:

private <T> void useInstanceMethodReferenceOnDifferentObjectThanItsSource(Supplier<String> instanceMethodReference, T object) {
    Function<T, String> classMethodReference = /* some magical conversion */ instanceMethodReference;
    System.out.println("Instance reference call result = " + classMethodReference.apply(object));
}

Is it at all possible? Byte-code wizardry like using cglib or even shady "hacks" are an acceptable answer.

0

There are 0 answers