Does anyone know a library or some at least some research on creating and using persistent data structures in Java? I don\'t refer to persistence as long term storage but persis
Follow a very simple tentative with dynamic proxy:
class ImmutableBuilder {
static T of(Immutable immutable) {
Class> targetClass = immutable.getTargetClass();
return (T) Proxy.newProxyInstance(targetClass.getClassLoader(),
new Class>[]{targetClass},
immutable);
}
public static T of(Class aClass) {
return of(new Immutable(aClass, new HashMap()));
}
}
class Immutable implements InvocationHandler {
private final Class> targetClass;
private final Map fields;
public Immutable(Class> aTargetClass, Map 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 newFields = new HashMap(fields);
newFields.put(fieldName, args[0]);
return ImmutableBuilder.of(new Immutable(targetClass, newFields));
} else {
return fields.get(fieldName);
}
}
public Class> getTargetClass() {
return targetClass;
}
}
usage:
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);
}
}
grow directions:
hope it helps :)