Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I override toString method of functional interface in JDK8 using lambdas [duplicate]

Can I override toString method of functional interface? Or rephrase. Is there elegant way to change anonymous inner class that implements functional interface and overrides toString method with lambdas? Can I override toString when I create lamba expression in JDK8.

interface Iface {
    void do();
}

main() { 
    Iface iface = () -> /*do something*/
    System.out.println(iface); // I would like to see anything useful in output
}

Can I override toString for iface?

like image 339
Andrei N Avatar asked Dec 18 '25 19:12

Andrei N


1 Answers

If you own the interface, you can do something like this

public interface Iface {
    void doIt();

    default Iface withToString(final String toString) {
        return new Iface(){
            public void doIt(){
                Iface.this.doIt();
            }

            public String toString(){
                return toString;
            }
        };
    }
}

public static void main(String... args){
    Iface iface = () -> {};
    iface = iface.withToString("anything useful");
    System.out.println(iface); // prints "anything useful" to output
}

Of course in practice it's fun to use something more interesting than just a String. It's not too much more code to capture the arguments and return value from doIt (if there were any) and generate a custom string with another functional interface.

like image 170
Fuwjax Avatar answered Dec 20 '25 10:12

Fuwjax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!