Home > Net >  How to pass a method invocation to a method (Java 8)
How to pass a method invocation to a method (Java 8)

Time:01-02

My original code looked like this:

SpecificEntity result = broker.changeSpecificEntity ( myTestKey , myTestData ) ;

"broker" is an (interface/implementation facade) with several methods (create, change, remove, etc) for each of many entity types.

I want to implement a generic version of the code so I don't have to repeat myself. There is more code than shown here, but the rest is already generic.

This is what we have so far.

public < K extends Key , D extends Data > D changeAnyEntity ( final K testKey, final D testData, BiFunction<K, D, D> brokerMethod ) 
{
    return brokerMethod.apply ( testKey , testData ) ;
}

Now I need to invoke a generic method, (e.g., changeAnyEntity) for each of the methods under test.

SpecificEntity result = changeAnyEntity ( myTestKey , myTestData , myBrokerFuncion )

I have not yet figured out how to define / create "myBrokerFunction"

CodePudding user response:

Create an interface with a single method accepting your wanted arguments and returning the type you need. Then you can use that interface as a parameter type, and you can avoid all unnecessary casting inside your generic method. The reason for making it generic is to avoid "knowing" about all individual child types after all

@FunctionalInterface
interface BrokerFun<KK, DD> {
    DD changeEntity(KK key, DD data);
}

public < K extends Key , D extends Data > boolean changeAnything (
        final K testKey,
        final D testData,
        BrokerFun<K, D> brokerFun
) {
    try {
        D result = brokerFun.changeEntity(testKey,testData);
        return isEqualCriticalFields(result, testData);
    } catch ( final Exception e ) {
        return false ;
    }
}

EDIT(Adding a BiFunction solution)

Alternatively you can use the BiFunction interface like this

public < K extends Key , D extends Data > boolean changeAnything (
        final K testKey,
        final D testData,
        BiFunction<K, D, D> brokerFun
) {
    try {
        D result = brokerFun.apply(testKey,testData);
        return isEqualCriticalFields(result, testData);
    } catch ( final Exception e ) {
        return false ;
    }
}

CodePudding user response:

Finally . . . ignoring try/catch logic

final BiFunction < SpecificEntityKey , SpecificEntityData , SpecificEntityData >
brokerMethod = ( k , d ) -> { myBroker.changeSpecificEntity ( k , d , null ) ; return d ; } ;
  • Related