[英]Method reference static vs non static
I've wondered how to distinct between static and non static method references with the same name. 我想知道如何区分具有相同名称的静态和非静态方法引用。 In my example I have a class called
StringCollector
that has the following three methods: 在我的例子中,我有一个名为
StringCollector
的类,它有以下三种方法:
StringCollector append(String string)
static StringCollector append(StringCollector stringCollector, String string)
StringCollector concat(StringCollector stringCollector)
Now if I want to use a Stream<String>
to collect a list of strings I would write something like that: 现在,如果我想使用
Stream<String>
来收集字符串列表,我会写出类似的东西:
Arrays.asList("a", "b", "c").stream()
.collect(StringCollector::new, StringCollector::append, StringCollector::concat);
As we can see the code doesn't compile. 正如我们所看到的,代码无法编译。 I think that's because the compiler can't deside, which method to use because each of them would match the functional.
我认为这是因为编译器无法决定使用哪种方法,因为它们中的每一种都与功能相匹配。 The question is now: Is there any possible way to distinct static method references from instance method references?
现在的问题是:是否有任何可能的方法来从实例方法引用中区分静态方法引用?
(PS: Yes the code compiles if I rename one of the two methods. For each of them.) (PS:是的,如果我重命名两种方法中的一种,代码就会编译。对于每种方法。)
In this case unbound reference to the instance method append
has the same arity, argument types and even return value as the reference to the static method append
, so no, you cannot resolve the disambiguation for method references. 在这种情况下,对实例方法
append
未绑定引用具有相同的arity,参数类型甚至返回值作为对静态方法append
的引用,所以不,您无法解决方法引用的消歧。 If you don't want to rename one of the methods, you should use lambda instead: 如果您不想重命名其中一个方法,则应该使用lambda:
collect(StringCollector::new, (sb, s) -> sb.append(s), StringCollector::concat);
Or if you actually want to use static method: 或者,如果您确实想使用静态方法:
collect(StringCollector::new, (sb, s) -> StringCollector.append(sb, s),
StringCollector::concat);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.