mardi 24 mai 2016

Java: Calling a method by reflection in a functional interface

does anyone know, if i can invoke a method by reflection in the body of a functional interface?

I want to return a predicate. So the typical syntax would be for example

Predicate<Data> pred = data -> data.getVar1().equals("foobar");

But in my special case neither the class nor the method to call is known since it's variable.

So I wanted to get something like this:

Method method = Class.forName("Data").getMethod("getVar1", (Class[]) null);
Predicate<T> pred = data -> 
                  ((String) method.invoke(data, (Object[]) null)).equals("foobar");

But Eclipse says: "Not handled TargetInvocationException". So I surrounded it with try-catch, but Eclipse shows already the same message.

Does anyone have a clue for me?





Aucun commentaire:

Enregistrer un commentaire