java - 错误: cannot use raw constructor reference with explicit type parameters for constructor

标签 java compiler-errors

我有以下代码:

Main.java

public class Main {
  public static void main(String[] args) {
     TestProducer c = Test::<String>new;
     System.out.println(c.produce("Point"));
  }
}

Test.java

public class Test<N extends CharSequence> {
  private CharSequence name;

  public Test(N k) {
    name = k;
  }

  public String toString() {
    return name.toString();
  }
}

TestProducer.java

@FunctionalInterface
public interface TestProducer {
  public <N extends CharSequence> Test<N> produce(N str);
}

当我编译代码时,它会产生以下错误:

OpenJDK Runtime Environment (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.4)
> javac -classpath .:/run_dir/junit-4.12.jar -d . Main.java Test.java TestProducer.java
Main.java:3: error: invalid constructor reference
     TestProducer c = Test::<String>new;
                      ^
  cannot use raw constructor reference with explicit type parameters for constructor
1 error
compiler exit status 1

我有以下问题:

  1. 这里的“原始构造函数引用”是什么(这里的“显式类型参数”是 <String>)?
  2. 为什么你不能“使用原始构造函数引用和构造函数的显式类型参数”(推理/为什么这不是一个好主意)?
  3. 如何修复此错误(创建仅接受 String s 的 TestProducer)?

编辑:

关于避免错误,这是我发现的:
我可以修改TestProducer到以下内容:

@FunctionalInterface
public interface TestProducer<N extends CharSequence>
{
  public Test<N> produce(N str);
}

然后更改Main.java像这样:

public class Main {
  public static void main(String[] args) {
     TestProducer<String> c = Test::new;
     System.out.println(c.produce("Point"));
  }
}

通过这样做,c::produce只接受String s,这符合我对问题3的意图。问题1和2仍然不清楚。

最佳答案

您定义您的TestProducer接口(interface)本身不是通用的,但有一个通用方法:

Test<N> produce(N str);

然后您尝试在赋值中绑定(bind)特定类型:

TestProducer c = Test::<String>new;

但我现在这样说是完全正确的:

c.produce(new StringBuilder())

必须返回Test<StringBuilder> ,不是Test<String> .

您可能应该添加 N作为接口(interface)上的类型参数。

关于java - 错误: cannot use raw constructor reference with explicit type parameters for constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57678819/

相关文章:

java - 在按钮中插入字符数组

java - hibernateentityManagerFactory init 抛出 ExceptionInInitializerError java.lang.ClassCastException

java - Jboss EAP 6模块热部署

excel - 编译错误: loop without do. But Do is in the code what is wrong?的代码

c++ - 错误:'std::cin 中的 'operator>>' 不匹配

inheritance - Typescript 不允许具有不同构造函数签名的类的 typeof 继承

java - 不完整的类型 :<anonymous ActionListener>cannot be converted to component

java - 带有链接列表的学生数据库

java - 在 libgdx 中处理多点触控

javascript - CoffeeScript 出现意外缩进错误