简体   繁体   English

如何将方法转换为 lambda 引用

[英]How to convert a Method into a lambda reference

I'm writing some jUnit5 extensions to make it easier to test some code.我正在编写一些 jUnit5 扩展,以便更轻松地测试某些代码。 The extension has these annotations:该扩展具有以下注释:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Test
@ExtendWith({CustomJunit5Extension.class})
public @interface MyAnnotation {
   String jsonFile;
   Class<?> converter;
}

// test case
class Test {
   @MyAnnotation(converter = MyClass.class)
   void someTest();
}

// Some class which contains a converter method annotated with @JsonConverterMethod
public class MyClass {
    @JsonConverterMethod
    public static Car converter(String jsonLine);
}

// jUnit5 extension
public class CustomJunit5Extension implements ParameterResolver, AfterEachCallback, AfterAllCallback {

   // ultra simplified version
   public Object resolveParameter(ParameterContext pctx, ExtensionContext ectx) throws ParameterResolutionException {
      final MyAnnotation annotation = getAnnotation(pctx, ectx);
      final Method converterMethod = getMethodByAnnotation(annotation.converter(), JsonConverterMethod.class);

      @SuppressWarnings({"unchecked"})
      final var converter = needs to become a 
                            direct reference to MyClass::converter
                            without hardcoding it, because you can
                            have other classes providing different
                            jsonString to Object converters;

      final JsonCandleProvider provider = new JsonCandleProvider(resource, converter);

      return provider;
   }

}

Hence the question - how to convert a Method reference into a Lambda reference so I could pass it to the MyJsonProvider ?因此问题 - 如何将Method引用转换为Lambda引用,以便我可以将它传递给MyJsonProvider Or how would you achieve a similar result in another way maybe?或者您将如何以另一种方式获得类似的结果?

The method parameter needs to be a Functional interface of the type of the method reference.方法参数需要是方法引用类型的功能接口。

MyMethod(() -> "Hello, World!");

Supplier<String> supplier = () -> "Hello, World!";
MyMethod(supplier);
MyMethod(supplier::get);
MyMethod2(supplier.get());


public static void MyMethod(Supplier<String> sup) {
    System.out.println(sup.get());
}

public static void MyMethod2(String value) {
    System.out.println(value);
}

prints印刷

Hello, World!
Hello, World!
Hello, World!
Hello, World!

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

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