I would like to lookup the methods of a class at runtime and use them as parameters where a functional parameter is required. Is this possible without wrapping a call to method.invoke(...)
with an implementation of the functional interface?
For example consider the functional interface
@FunctionalInterface
public interface MyFunction<T> {
void apply(T param);
}
a method like
public <T> void doSomething(MyFunction<T> func) { /* ... */ }
and a class
public class MyClass {
public void myMethod(Object arg) { /* ... */ }
}
now I could call doSomething
like this
MyClass myObj = new MyClass();
doSomething(myObj::myMethod);
I would like to do exactly this using reflection with the smallest possible performance penalty. I am able to do it like
final Method myMethod = ...
MyFunction<?> wrapper = param -> {
try {
myMethod.invoke(param);
} catch (Exception e) { /* handle e */ }
};
doSomething(wrapper);
But I am wondering if there is a better alternative (except not using reflection at all).
Aucun commentaire:
Enregistrer un commentaire