本文介绍了Java方法引用具有泛型参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对一个方法进行方法引用,该方法在类声明中指定了泛型参数。
所以我有:

I'm trying to make a method reference to a method which have a generic parameter specified in a class declaration.So I have:

public interface IExecutable<P extends IParameter> {

    void execute(P parameter);

}

public class Parameter implements IParameter {

    public void childSpecific() {
    ...
    }
}

public class TestClass {
    ...
    //somewhere in the code
    public void foo(Parameter parameter) {
        parameter.childSpecific();
    }

    public void test() {
        IExecutable<?> executable = this::foo; //compilation error
        // The type TestClass does not define inner(IParameter) that is applicable here
        executable.execute(new Parameter()); //compilation error as well
        // The method execute(capture#4-of ?) in the type IExecutable<capture#4-of ?> is not applicable for the arguments (Parameter)
    }
    ...
}

具体是我不知道可执行文件的具体泛型类型。使用

It's specific that I don't know the concrete generic type of the executable here. Using

IExecutable<Parameter> = ...

立即解决问题,但案件不可能。

solves the problem immediately, but it's impossible for the case.

显然,我做错了什么。但是如何使它工作?

Clearly, I'm doing something wrong. But how to make it work?

Thx。

推荐答案

In在这种情况下,foo不会被写入处理参数以外的任何 IParameter 。您可以将对foo的引用分配给类型为 IExecutable<?的变量扩展IParameter> ,但这意味着它是一个可执行文件,处理一些未知类型的 IParameter (在这种情况下,参数)。由于特定的子类型是未知的,因此将 IParameter 的任何子类型传递给其execute方法在语法上是不安全的,因为您不知道它可以在此处理范围!

In this case, foo is not written to handle any IParameter other than Parameter. You could assign a reference to foo to a variable of type IExecutable<? extends IParameter>, however this means that it is an executable that handles some unknown type of IParameter (in this case, Parameter). Since the specific subtype is unknown, it would not be syntactically safe to pass any subtype of IParameter in to its execute method, since you don't know which it can handle within this scope!

您需要的是另一种类型变量而不是使用捕获(?)。这样,您可以指定传入的 IParameter 与可执行文件接受的 IParameter 的类型相同。您可以使用一种新方法来介绍它,就像我在下面所做的那样:

What you need is another type variable instead of using a capture (the ?). This way you can specify that the IParameter you're passing in is the same type as the IParameter the executable accepts. You could introduce this with a new method, like I'm doing below:

public class TestClass {
  public static void foo(Parameter parameter) {
    parameter.childSpecific();
  }

  public static void main(String args) {
    execute(TestClass::foo, new Parameter());
  }

  public static <P extends IParameter> void execute(
        IExecutable<P> executable, P param) {
    executable.execute(param);
  }
}

这篇关于Java方法引用具有泛型参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-19 05:09