A1m
A1m

Reputation: 3107

Get Method reference from Method object

I have a method that expects a method reference:

expectsMethodRef(obj::someMethod);

I now only retrieve the method at compiletime with reflection. How do I get the method reference from a Method object?

Method method = obj.class.getMethod(methodNameStr);
expectsMethodRef(<how to input my method here?>);

Upvotes: 2

Views: 1051

Answers (1)

tsolakp
tsolakp

Reputation: 5948

You just need to use Method.invoke. Here is an example:

public class SomeObject{

    public String someMethod(){
        return "Test";
    }
}

public String expectsMethodRef( Function<SomeObject, String> f ){
    SomeObject so = new SomeObject();
    return f.apply(so);
}

And here is how you invoke using plain lambda and Method object.

    //plain lmbda
    expectsMethodRef( SomeObject::someMethod  );

    //with method object
    Method someMethod = SomeObject.class.getMethod("someMethod");        
    expectsMethodRef( (so) -> {
        try {
            return (String)someMethod.invoke(so);
        } catch (Exception e) {
            return null;
        }
    } );

Upvotes: 7

Related Questions