简体   繁体   中英

Is it possible to detect if fluent interface was called for the first time?

Let's say I have a class:

class A {
    public A fun() {
        System.out.println("a");
        return this;
    }   
}

And a scenario:

A a = new A();
a.fun().fun().fun().fun();
a.fun().fun();

Is it somehow possible to print additional message in the first call of each sequenced calls without adding something like .start() / .finalize() ?

You could do something like this:

public class A {

    public A fun() {
        System.out.println("A");
        return new AA();
    }

    private class AA extends A {
        @Override
        public A fun() {
            System.out.println("AA");
            return this;
        }
    }

    public static void main(String[] args) {
        A a = new A();
        a.fun();
        a.fun().fun();
        a.fun().fun().fun();
    }
}

Outputs:

A
A
AA
A
AA
AA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM