Given a class consisting of static predicate methods, I want to access them via reflection and convert them to Predicate<Object>
type.
public class MyPredicates {
public static boolean isNull(Object obj) {
return obj == null;
}
public static boolean hasNegativeHashcode(Object obj) {
return obj.hashCode() < 0;
}
}
Normally, I would write the following code to get the predicate:
Predicate<Object> isNull = MyPredicates::isNull;
However, I don't know how to do that using reflection. My intention is to create an annotation for these methods and get them via reflection to create a list of available predicates for my framework.
I thought of three possible approaches, none of which seems good to me.
- I could leave it like
Method
, callinvoke()
and cast the returnedObject
toboolean
. This, however, would be hard to read and it would mean that I'd have no way of checking the type during runtime. - I could wrap the reflection call to
Predicate
but this would involve additional overhead. - I could make the user to register every method separately (hard to maintain when adding/removing many methods).
In any case, I fear that using reflection directly will add more overhead and slow down the program.
So, my questions are:
- Can I get the
Predicate
via reflection directly? - If not, what would be an appropriate way of accessing such methods without adding too much overhead, while having a usable API (e.g. by involving
Predicate
)?
Aucun commentaire:
Enregistrer un commentaire