简体   繁体   English

如何将方法调用传递给方法 (Java 8)

[英]How to pass a method invocation to a method (Java 8)

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.代码比这里显示的要多,但是 rest 已经是通用的了。

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, (eg, changeAnyEntity) for each of the methods under test.现在我需要为每个被测方法调用一个通用方法(例如,changeAnyEntity)。

SpecificEntity result = changeAnyEntity ( myTestKey , myTestData , myBrokerFuncion )

I have not yet figured out how to define / create "myBrokerFunction"我还没有弄清楚如何定义/创建“myBrokerFunction”

Create an interface with a single method accepting your wanted arguments and returning the type you need.使用单一方法创建一个接口,接受您想要的 arguments 并返回您需要的类型。 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)编辑(添加 BiFunction 解决方案)

Alternatively you can use the BiFunction interface like this或者,您可以像这样使用 BiFunction 接口

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 ;
    }
}

Finally.最后。 . . . . ignoring try/catch logic忽略 try/catch 逻辑

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM