如何在Java 8中创建一个lambda表达式来定义toString? [英] How to make a lambda expression define toString in Java 8?
问题描述
我不希望有一个正常的lambda实现一个方法,并将它的toString重新定义为一个附加值。我希望lambda表达式只实现toString方法。
我知道我的表达不是很好,但我相信你会理解这个例子。
I don't want to have a normal lambda implementing a method and redefine it's toString as a added value. I want the lambda expression implement only the toString method. I know I am not expressing it very well but I am sure you will understand me with this example.
public class LambdaToStringTest {
public interface ToStringInterface {
public abstract String toString();
}
public static void main(String[] args) {
print("TRACE: %s", (ToStringInterface)()->someComputation()); // <<-- ERROR: The target type of this expression must be a functional interface
}
private static void print(String format, Object... args) {
System.out.println(String.format(format, args));
}
}
如果我更改名称,它会编译该方法然后它不会覆盖toString,因此print方法将不会打印预期的内容。
It compiles if I change the name of the method but then it does not override toString so print method will not print what is expected.
这是尝试定义仅在需要时评估lambdas的日志子系统(当它真的要打印时)但与非lambda参数兼容。我知道其他方法来实现它,但我想知道为什么我不能这样做,如果有解决方法或我做错了什么,
This is an attempt to define a log subsystem that evaluates lambdas only when needed (when it is really going to be printed) but being compatible with non-lambda arguments. I know other ways to achieve it but I wonder why I can't do it this way and if there is a workaround or I am doing something wrong,
推荐答案
简短回答,你不能。 @FunctionalInterface
s不能用于覆盖来自 Object
的方法。
Short answer, you can't. @FunctionalInterface
s cannot be used to "override" methods from Object
.
但是,您可以使用虚拟扩展方法实现 Formattable
。注意:下面的代码是UNTESTED:
You can implement Formattable
however, with a virtual extension method. Note: code below is UNTESTED:
@FunctionalInterface
public interface ToStringInterface
extends Formattable
{
String asString();
@Override
default void formatTo(Formatter formatter, int flags, int width, int precision)
{
formatter.format("%s", this);
// Or maybe even better:
formatter.out().append(this.asString());
}
}
我建议使用此解决方案,因为您使用 String.format()
使用此接口。
I propose this solution since you are using String.format()
which makes use of this interface.
或者您可以定义自己的界面。或者甚至为这个接口编写一个包装器,它在 .asString()
中调用 .toString()
。选择很多。
Or you can just define your own interface. Or even write a wrapper for this interface which calls .toString()
in .asString()
. Choices are many.
这篇关于如何在Java 8中创建一个lambda表达式来定义toString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!