Make id configurable
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RecordId {
}
public final class Scan {
public static final String recordIdFieldNameIn(Class klass) {
for (Field field : klass.getDeclaredFields()) {
if (field.isAnnotationPresent(RecordId.class)) {
return field.getName();
}
}
throw new RecordIdNotFoundException(klass);
}
}
public class RecordIdNotFoundException extends RuntimeException {
public RecordIdNotFoundException(Class klass) {
super("@" + RecordId.class.getSimpleName() + " not found on " + klass.getSimpleName());
}
}
public class MemoryStorage<T> implements Store<T> {
// Cached
private final String recordId;
protected final Map<Serializable, T> data = new HashMap<Serializable, T>();
protected final IdGenerator idGenerator;
public MemoryStorage(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
Class klass = (Class) ((ParameterizedType) getClass().getGenericInterfaces()[0]).getRawType();
recordId = Scan.recordIdFieldNameIn(klass);
}
...
/**
* {@inheritDoc}
*/
@Override
public void save(T item) {
Serializable newId = idGenerator.generate();
try {
Method setMethod = item.getClass().getMethod(recordId, Serializable.class);
setMethod.invoke(item, newId);
} catch (Exception e) {
// throw exception
}
data.put(newId, item);
}
}