Search code examples
javafluent-interface

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()?


Solution

  • 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