andi
andi

Reputation: 47

Get direct Java Method by Class Accessor

Is there some way to get a java.lang.reflect.Method object by direct access? Like MyUtils::sum in my example below:

class MyUtils {
    static int sum(int a, int b) {
        return a + b;
    }
}

java.lang.reflect.Method myUtilsSumMethod = MyUtils::sum;
int sum = myUtilsSumMethod.invoke(null, 2, 3); // should be 5

Or do I always have to use the string name using reflection API?

MyUtils.class.getDeclaredMethod("sum", Integer.class, Integer.class)

Because as soon as I refactor the name of the method, I will get an exception at Runtime and I would like to have the error already during compile time.

Upvotes: 1

Views: 100

Answers (1)

Mureinik
Mureinik

Reputation: 311028

You don't need reflection here - MyUtils::sum returns a method reference that you can store in an IntBinaryOperator:

IntBinaryOperator myUtilsSumMethod = MyUtils::sum;
int sum = myUtilsSumMethod.applyAsInt(2, 3); // should be 5

Upvotes: 2

Related Questions