javafunctional-interface

How to call a list of pre-defined interface methods on objects in Java?


Here's my problem. I have an interface with several getter methods and an implementation class.

Class MyInterface {
    String getA();
    String getB();
    ...
}

Class MyClass implements MyInterface {
}

I need to write some logic this to compare the values of the get methods between two objects of MyClass.

static List<Function> getters = List.of(MyInterface::getA, MyInterface::getB, ...); //this is hard-coded

for(Function getter : getters) {
    if(getter.apply(obj1).equals(getter.apply(obj2))
        //do something
}

However I try, I cant seem to get the syntax correct, and satisfy the "type" Gods. Please help.

With a @FunctionalInterface, I was able to get the List defined, although as a member variable and not static, like so.

@FunctionalInterface
interface GetterFunction {
    String get();
}

List<GetterFunction> allGetters = List.of(this::getA, this::getB, ...)

But this seems ugly and feels like there is a better way.

I also do not want to do Reflections.


Solution

  • Why put all the getters in a list? If you're hardcoding them anyway, might as well write out the checks:

    check(MyInterface::getA, obj1, obj2)
    check(MyInterface::getB, obj1, obj2)
    
    void <T> check(Function<MyInterface, T> getter, MyInterface obj1, MyInterface obj2) {
      if (getter.apply(obj1).equals(getter.apply(obj2)) {
        // ...
      }
    }