mardi 4 décembre 2018

How can I get Predicate from static methods via reflection?

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.

  1. I could leave it like Method, call invoke() and cast the returned Object to boolean. This, however, would be hard to read and it would mean that I'd have no way of checking the type during runtime.
  2. I could wrap the reflection call to Predicate but this would involve additional overhead.
  3. 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:

  1. Can I get the Predicate via reflection directly?
  2. 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