【问题标题】:How to declare a variable that accepts method reference of any type Function<>如何声明一个接受任何类型 Function<> 的方法引用的变量
【发布时间】:2021-08-30 12:34:35
【问题描述】:

我正在尝试声明一个接受任何类型的方法引用的变量Function

此方法引用将在映射器中使用,我接受一些输入并通过调用引用另一个对象的方法来映射相应的值。

@Data // Lombok
public class ReferenceSample<T, R> {

  private final Function<T, R > methodReference; // should be able to accept any method reference

}

以下是可能的方法

     public class Common {

          public static String getMethod1(String a) {
            // Process
            return "result1";
          }

          public static SomeEnum getMethod2(String b) {
            // Process
            return SomeEnum.DATA;
          }
        }

当我尝试创建对象时

new ReferenceSample(Common::getMethod1);

我收到以下错误

java: incompatible types: invalid method reference
    incompatible types: java.lang.Object cannot be converted to java.lang.String

【问题讨论】:

标签: java generics lambda


【解决方案1】:

您需要专门化泛型类型,如下所示。

public class Reference
{
    public static void main (String[] args)
    {
        Reference app = new Reference ();
        app.test ();
    }

    private void test ()
    {
        int[] row = {1, 1, 5, 2, 4};

        System.out.println ("Input: " + Arrays.toString (row));

        // This fails because the generic types have not been specified
        ReferenceSample rs1 = new ReferenceSample (Common::getMethod1);
        
        // This compiles but isn't specialized
        ReferenceSample<?, ?> rs2 = new ReferenceSample<> (Common::getMethod1);
        
        // This is preferred because it specifies the types precisely
        ReferenceSample<String, String> rs3 = new ReferenceSample<> (Common::getMethod1);
    }
}

class ReferenceSample<T, R>
{
    public Function<T, R> methodReference; // should be able to accept any method reference

    public ReferenceSample (Function<T, R> methodReference)
    {
        this.methodReference = methodReference;
    }
}

class Common
{
    public static String getMethod1 (String a)
    {
        // Process
        return "result1";
    }

    public static String getMethod2 (String b)
    {
        // Process
        return "+" + b + "+";
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-24
    • 2019-08-28
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    相关资源
    最近更新 更多