抽象类的 Lambda 表达式 [英] Lambda Expressions for Abstract Classes
问题描述
我有一个带有一个抽象方法的抽象类.我如何使用 lambda 表达式来实例化它.它不能被做成接口,因为它扩展了一个类.
I have an abstract class with one abstract method. How can I use lambda expressions to instantiate it. It cannot be made into an interface because it extends a class.
public class Concrete<T> {
// Has a bunch of predefined methods.
}
public abstract class Abstract<T> extends Concrete<T> {
public T getSomething();
// Uses inherited methods from Concrete class
}
public class Driver {
public static void main(String[] args) {
System.out.println(new Abstract<String>() {
public String getSomething() {
// Returns something using inherited methods from Abstract
// Class and Concrete Class
}
});
}
}
推荐答案
正如 Sleiman Jneidi 在他的回答中指出的那样,您不能直接使 lambda 表达式目标为抽象类.但是,您可以使用一种解决方法:
You cannot directly make a lambda expression target an abstract class, as Sleiman Jneidi pointed out in his answer. However, you can use a workaround:
public class AbstractLambda<T> extends Abstract<T>
{
private final Supplier<? extends T> supplier;
public AbstractLambda(Supplier<? extends T> supplier)
{
this.supplier = supplier;
}
@Override
public T getSomething()
{
return this.supplier.get();
}
}
这可以与 lambda 表达式一起使用:
This can be used with a lambda expression:
Abstract<String> a = new AbstractLambda<>(() -> "Hello World");
System.out.println(a.getSomething()); // prints 'Hello World'
如果您的 getSomething(...)
方法有参数,请使用 java.util.function.Function
或 java 中的相应接口.util.function
包而不是 java.util.function.Supplier
.
In case your getSomething(...)
method has arguments, use a java.util.function.Function
or the appropriate interface from the java.util.function
package instead of java.util.function.Supplier
.
这也是 java.lang.Thread
让您使用 Runnable
lambda 而不必子类化类的方式:
This is also how the java.lang.Thread
lets you use a Runnable
lambda instead of having to subclass the class:
Thread t = new Thread(() -> System.out.println("Hello World"));
t.start();
这篇关于抽象类的 Lambda 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!