Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Follow a very simple tentative with dynamic proxy: </p> <pre><code>class ImmutableBuilder { static &lt;T&gt; T of(Immutable immutable) { Class&lt;?&gt; targetClass = immutable.getTargetClass(); return (T) Proxy.newProxyInstance(targetClass.getClassLoader(), new Class&lt;?&gt;[]{targetClass}, immutable); } public static &lt;T&gt; T of(Class&lt;T&gt; aClass) { return of(new Immutable(aClass, new HashMap&lt;String, Object&gt;())); } } class Immutable implements InvocationHandler { private final Class&lt;?&gt; targetClass; private final Map&lt;String, Object&gt; fields; public Immutable(Class&lt;?&gt; aTargetClass, Map&lt;String, Object&gt; immutableFields) { targetClass = aTargetClass; fields = immutableFields; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("toString")) { // XXX: toString() result can be cached return fields.toString(); } if (method.getName().equals("hashCode")) { // XXX: hashCode() result can be cached return fields.hashCode(); } // XXX: naming policy here String fieldName = method.getName(); if (method.getReturnType().equals(targetClass)) { Map&lt;String, Object&gt; newFields = new HashMap&lt;String, Object&gt;(fields); newFields.put(fieldName, args[0]); return ImmutableBuilder.of(new Immutable(targetClass, newFields)); } else { return fields.get(fieldName); } } public Class&lt;?&gt; getTargetClass() { return targetClass; } } </code></pre> <p>usage:</p> <pre><code>interface Person { String name(); Person name(String name); int age(); Person age(int age); } public class Main { public static void main(String[] args) { Person mark = ImmutableBuilder.of(Person.class).name("mark").age(32); Person john = mark.name("john").age(24); System.out.println(mark); System.out.println(john); } } </code></pre> <p>grow directions:</p> <ul> <li>naming policy (getName, withName, name) </li> <li>caching toString(), hashCode()</li> <li>equals() implementations should be straightforward (although not implemented)</li> </ul> <p>hope it helps :)</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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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