Note that there are some explanatory texts on larger screens.

plurals
  1. POIn java, can one create a fluent extensible class hierarchy with methods that can be invoked in any order?
    primarykey
    data
    text
    <p>Can one create an extensible class hierarchy in java whose methods are fluent and can be invoked in any order? <strong><em>(YES! see answer below), even for existing classes when you don't have access to the source, provided the methods are fluant!</em></strong></p> <p>I'm retrofitting an existing hierarchy and hope to use a factory or at least a generic constructor and (eventually) immutable builder patterns <em>(JB P.14).</em> The methods that set fields return <code>void</code> - it would be better for them to return a generic <code>T</code> instead - that way we will gain the ability to do method chaining (they all call <code>super</code> now). </p> <p>Goals:<br> 1. <strong>Avoid having to create a static getFactory() method in every class.</strong><br> 2. <strong>Simple method signatures.</strong><br> 3. <strong>Create a factory method that is generic, yet will catch problems at compile time.</strong><br> 4. <strong>Get compile time errors instead of run time errors when mistakes are made.</strong> </p> <p>As requested, the non-generic code is very simple, but doesn't work.</p> <pre><code>public class A { private String a = null; protected A setA(String a){ this.a = a; return this;//&lt;== DESIRE THIS TO BE CHAINABLE } protected static A factory(){ return new A(); } } </code></pre> <p>.</p> <pre><code>public class B extends A { private String b = null; protected Foo setB(String b){ this.b = b; return this;//&lt;== DESIRE THIS TO BE CHAINABLE } protected static B factory(){ return new B(); } } </code></pre> <p>Now a caller could TRY to call <code>B.factory().setA("a").setB("b")//won't compile</code></p> <p>But that can't compile because <code>setA()</code> returns an <code>A</code>, not a <code>B</code>. You COULD make it work by overriding the <code>setA()</code> in <code>B</code>, calling <code>setB()</code> and returning <code>B</code> instead of the <code>A</code>. To avoid delegating for each of those methods is the point. I simply want an extensible group of chainable class methods that can be invoked in any order. <code>B.getFactory().B("b").A("a")</code> works obviously.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload