Java Generics Type DSL with Builder Pattern -


i try create dsl java api builder pattern on generics type.

i have following class:

public class rule<t> {    private predicate<t> condition;    public conditionbuilder<t> when() {     return new conditionbuilder<>(this);   }    //setter , getter   } 

and following conditionbuilder class:

public class conditionbuilder<t> {    private rule<t> parent;    public conditionbuilder(rule<t> parent) {     this.parent = parent;   }    public conditionbuilder<t> condition1() {     parent.setcondition(l -> l == 0); // integer     return this;   }    public conditionbuilder<t> condition2() {     parent.setcondition(l -> l.length() > 3); // string     return this;   }  } 

i try find solution set generic type on fly integer (resp. string) condition1 (resp. condition2).

is there pattern or solution avoid doing instanceof checking ?

you can't member methods on conditionbuilder<t>, since you've constructed parent before invoke either of conditionx methods. such, can't constrain instance "after fact".

the way i'd making rule<t> parameter of static method. can use like:

static conditionbuilder<integer> condition1(conditionbuilder<integer> parent) {   parent.setcondition(l -> l == 0);   return parent; }  static conditionbuilder<string> condition2(conditionbuilder<string> parent) {   parent.setcondition(l -> l.length() > 3);   return parent; } 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -