如何使 lambda 表达式在 Java 8 中定义 toString? [英] How to make a lambda expression define toString in Java 8?

查看:31
本文介绍了如何使 lambda 表达式在 Java 8 中定义 toString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想让一个普通的 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,因此打印方法不会打印预期的内容.

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.

这是尝试定义一个日志子系统,该子系统仅在需要时(当它真正要打印时)评估 lambda,但与非 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,

推荐答案

简而言之,你不能.@FunctionalInterfaces 不能用于覆盖"来自 Object 的方法.

Short answer, you can't. @FunctionalInterfaces cannot be used to "override" methods from Object.

您可以使用虚拟扩展方法实现 Formattable.注意:以下代码未经测试:

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.

这篇关于如何使 lambda 表达式在 Java 8 中定义 toString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆