Note that there are some explanatory texts on larger screens.

plurals
  1. POGeneric Type From Enum & The Builder Pattern
    primarykey
    data
    text
    <p>I'm trying to create a builder pattern that uses generics to provide type checking on some of the methods. Currently I have the following working:</p> <pre><code>ParameterBuilder.start(String.class).setName("foo").setDefaultValue("Hello").build(); ParameterBuilder.start(Integer.class).setName(bar).setDefaultValue(42).build(); ParameterBuilder.start(Boolean.class).setName(bar).setDefaultValue(false).build(); </code></pre> <p>Using the code:</p> <pre><code>public class ParameterBuilder&lt;T&gt; { private String name; private T defaultValue; public static &lt;T2&gt; ParameterBuilder&lt;T2&gt; start(Class&lt;T2&gt; type) { return new ParameterBuilder&lt;T2&gt;(); } // Other methods excluded for example } </code></pre> <p>So the type of the input for the <code>setDefaultValue</code> method is defined by what's passed into the <code>start</code> method, just as I want.</p> <p>But now I want to extend what's being passed into <code>start()</code> to contain a little more information. Essentially I want to pass in a "type" for the parameters I creating. Sometimes these parameters will be things like "email", "url" etc. The default value will still be of a known type (String in those cases), so I'd like to have something like:</p> <pre><code>ParameterBuilder.start(EMAIL).setName("email").setDefaultValue("foo@bar.com").build(); ParameterBuilder.start(URL).setName("website").setDefaultValue("http://www.somewhere.com").build(); </code></pre> <p>Where at the moment EMAIL &amp; URL are enums, containing amongst other things - the class of the default value. But if I go down this route, how would I instantiate the parameter builder?</p> <pre><code>public static &lt;T2&gt; ParameterBuilder&lt;T2&gt; start(ParameterType paramType) { Class&lt;T2&gt; type = paramType.getTypeClass(); // How do I instantiate my ParameterBuilder with the right type? } </code></pre> <p>If it can't be done using enums (which I can see being the case), does anyone have a suggestion for a different solution?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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