我在处理一些旧代码时偶然发现了一个问题,用 lambda 表达式或方法引用替换了几个匿名类。这个问题有点难以用语言解释,但我会尽力而为,并且我还在下面添加了一个简短的示例,尽我所能来说明我的问题。
我的例子包括...
函数式接口GenericListener接受类型参数 V并具有单个方法“genericCallback(V genericValue)”。
一个类CallbackProducer,它采用类型参数 T。该类还有一个方法来添加 Integer 类型的 GenericListener。
一个Main类,它创建 CallbackProducers 并向其中添加 GenericListeners。
当我从 Main 的构造函数运行 CallbackProducer 的 addIntegerListener 方法时,只要我避免指定 CallbackProducer T 的类型,就会收到编译器错误:“不兼容的类型”。
addIntegerListener 方法仅使用 GenericListener 的 V。据我所知,它没有以任何方式使用 CallbackProducer 的 T。
我在 Main 的构造函数中多次调用 addIntegerListener + 注释,其中 3 次调用导致编译器错误。但据我所知(根据 IntelliJ),所有这些都应该是合法的。如果您注释掉对 addIntegerListener 的第 3 个调用,应用程序将编译并运行得很好。
另外,如果 CallbackProducer 不使用泛型,并且我们完全删除了类型参数 T,则对 addIntegerListener 的第 3 次调用将编译。
这种行为有原因吗?我是否误解了什么,或者这是java编译器的弱点或错误?(我目前使用的是java 1.8_51)
预先感谢您的任何澄清!
import javax.swing.*;
public class Main {
public static void main(final …Run Code Online (Sandbox Code Playgroud) 我对该方法参考语法有些困惑。
counter()预计一BiFunction不过HighTemp::lessThanTemp是,尽管有效的参数HighTemp.lessThanTemp()只带一个参数。
该行中到底发生了if (f.func(vals[i], v))什么?
MCVE:
import java.util.function.BiFunction;
class Demo {
static class HighTemp {
private int hTemp;
HighTemp(int ht) { hTemp = ht; }
boolean lessThanTemp(HighTemp ht2) {
return hTemp < ht2.hTemp;
}
}
static <T> int counter(T[] vals, BiFunction<T,T,Boolean> f, T v) {
int count = 0;
for (int i=0; i < vals.length; i++) {
if (f.apply(vals[i], v)) { // THIS LINE
count++;
}
}
return count;
}
public …Run Code Online (Sandbox Code Playgroud) 是否有一种简便的方法来获取对本地静态方法的方法引用,就像this调用方法时可以删除关键字或类前缀一样?
显而易见的是使用::myStaticMethod但似乎无法编译:
class MyClass {
static void myStaticMethod () {}
static Runnable runner = ::myStaticMethod; // doesn't compile
// requires MyClass prefix despite being in the same class
}
Run Code Online (Sandbox Code Playgroud) 对特定对象的实例方法的引用的概念是否破坏了 Java 中的类型安全?
根据
https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
你可以有一个不实现 Comparator 接口的自定义类比较提供者,并且仍然使用这个类的实例作为方法的第二个参数
Arrays.sort(T[] a, 比较器 c)
当然,ComparisonProvider 的实现必须有一个方法,其签名与 Comparator.compare() 方法完全匹配,但这仍然不是 Comparator 的实例,不是吗?
本质上,Java 8 允许我们使用类的实例,就好像它们正在实现特定的接口一样,而实际上它们不是。
这意味着,我们正在失去 Java 中的类型安全性,对吗?
我们正在尝试向collect我们目前定义的扩展Java Stream API 添加重载方法:
interface ExtendedStream<R> extends Stream<R> {
<R1> R1 collect(SerializableSupplier<Collector<? super R, ?, R1>> supplier);
}
Run Code Online (Sandbox Code Playgroud)
SerializableSupplier 被定义为:
interface SerializableSupplier<T> extends Serializable, Supplier<T> {
}
Run Code Online (Sandbox Code Playgroud)
使用lambda调用此collect方法工作正常,但使用方法引用调用它无法编译时出现以下错误:
Error:(50, 72) java: incompatible types: cannot infer type-variable(s) R1,capture#1 of ?,T
(argument mismatch; bad return type in method reference
java.util.stream.Collector<T,capture#1 of ?,java.util.List<T>> cannot be converted to java.util.stream.Collector<? super java.util.Map.Entry<java.lang.Integer,java.lang.String>,?,R1>)
Run Code Online (Sandbox Code Playgroud)
我在这里创建了一个独立的Java类,您可以将其加载到编译器中以进行尝试.
我目前正在使用Java版本:
java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed …Run Code Online (Sandbox Code Playgroud) 根据JLS methodReferenceOfNullObject()调用时正确的行为是什么?
NullPointerException(Oracle Java Compiler)或指定供应商,result虽然o是null(Eclipse的Java编译器)
public void methodReferenceOfNullObject() {
Object o = nullReference();
Supplier<String> result = o::toString; // <-- point of interest
...
}
private Object nullReference() {
return null;
}
Run Code Online (Sandbox Code Playgroud)在以下代码中,
class IncWrapper<T> (val wrapped: T, val base: Int) {
fun incFunction(increment: Int, func: T.(Int) -> Int): Int {
return increment + wrapped.func(base)
}
}
class ClassWithIndecentlyLongName {
fun square(x: Int) = x * x
}
fun main() {
val wrapper = IncWrapper(ClassWithIndecentlyLongName(), 2)
val computed = wrapper.incFunction(1, ClassWithIndecentlyLongName::square)
println(computed)
}
Run Code Online (Sandbox Code Playgroud)
我们传递了对包装类方法的引用ClassWithIndecentlyLongName。由于在调用站点上知道此类应作为方法的接收者,因此再次传递该类的名称似乎很尴尬/多余。我希望有些事情::square能奏效,但事实并非如此。如果缺少此功能,可能是什么原因?
(这个问题源于试图重构一些冗长的Java代码,将一类的许多字段转换为另一类的代码。)
在 Java 中使用流时,是否可以使用方法引用进行算术加法(而不是 lambda)?
目前(总结流的内容)我正在使用stream.reduce(0, (x, y) -> x + y),但我想使用类似的东西stream.reduce(0, Math::add),如果它存在的话。
在更一般但类似的注释中,Java中的每个方法/操作是否都有方法引用?
我有一个我不明白的 java 编译器错误。似乎消费者< ? > 和 Consumer< T >(带有 T extends Object)在方法签名参数中是不等价的。请查看以下代码:
import java.util.function.Consumer;
public class MyClass {
public void joker(Consumer<?> fct) {}
public <T> void generic(Consumer<T> fct) {}
public void myConsumer(String s) {}
public void doesNotCompile()
{
joker(this::myConsumer); // COMPILE ERROR : (In Eclipse : ) The type MyClass does not define myConsumer(Object) that is applicable here
generic(this::myConsumer); // Works fine : how come are "T" and "?" not equivalent here ?
// The following also works fine as …Run Code Online (Sandbox Code Playgroud) 在 Java 中的实例方法的情况下,我无法掌握方法引用的概念
例如,在下面的示例中,编译器在列表行中给出错误。
我看过 String::toUpperCase 的例子。
我对 (1) String 是一个类而 toUpperCase 是实例方法这一点感到困惑。Java 允许 String::toUpperCase (2) 为什么在我的情况下不允许:- AppTest::makeUppercase
package mja;
import java.util.function.Function;
public class AppTest {
public String makeUppercase(String source){
return source.toUpperCase();
}
public void printFormattedString(String string, Function<String, String> formatter){
System.out.println(formatter.apply(string));
}
public static void main(String[] args) {
AppTest appTest = new AppTest();
String source = "Hello World!";
// Below statement compiled successfully
appTest.printFormattedString(source, appTest::makeUppercase);
// Getting error that non-static method can't be referenced from static context
appTest.printFormattedString(source, AppTest::makeUppercase);
} …Run Code Online (Sandbox Code Playgroud) method-reference ×10
java ×8
java-8 ×4
generics ×3
lambda ×2
ecj ×1
java-stream ×1
kotlin ×1
syntax ×1
type-safety ×1