【问题标题】:Unable to match generic types in method parameters无法匹配方法参数中的泛型类型
【发布时间】:2021-02-26 09:22:17
【问题描述】:

我不知道标题是否可以理解,但我有这个:

    public class Product {
        public Integer getId() {...}
        public String getName() {...}
    }

    public <T,V> static void method(Function<T, V> f, V value) {...}

并且我想在以下情况下出现编译错误:

    method(Product::getId, "some String"); // id is not String
    method(Product::getName, 123);         // name is not Integer

但编译器将 V 解释为:

java Serializable & Comparable<? extends Serializable & Comparable<?>>

它可以编译,但取决于“方法”的实现方式,您会在运行时收到异常,或者它只是工作错误。

如何指示编译器匹配所需的数据类型? 而且我不想为每种可能的 V 类型编写一个“方法”。

谢谢!

【问题讨论】:

  • this 回答你的问题了吗?
  • @AndrewVershinin 不是真的,因为他们建议实现 Object.equals 之类的方法,但它发生在运行时,我希望它在编译时。不过谢谢!

标签: java generics lambda


【解决方案1】:

您可以通过将泛型拆分为两个方法调用来强制执行泛型,因为您需要一个新类:

public class Value<T, V> {
    private final Function<T, V> f;
    
    public Value(Function<T, V> f) {
        this.f= f;
    }

    public void with(V value) {
        // move your code from method() into here
    }
}

然后将method() 更改为如下内容:

public static <T, V> Value<T, V> method(Function<T, V> f) {
    return new Value<>(f);
}

那么你可以这样使用它:

method(Product::getId).with("123");   // compiler error
method(Product::getName).with(123);   // compiler error
method(Product::getId).with(123);     // no error
method(Product::getName).with("123"); // no error

【讨论】:

  • 一个额外的类和一个额外的方法回调,但它可以解决问题。谢谢!
猜你喜欢
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多