This is the perfect use case for PropretyHolder , which I wrote a while ago. You can read more about this on my blog . I designed it with the same thing in mind, feel free to adapt it to your needs.
In general, I would say if you want to profit from type safety in Java, you need to know your keys. What I mean by this is hardly possible to develop a secure solution such as where keys come from an external source.
Here is a special key that knows the type of its value (it is not completed, please download the source for the full version):
public class PropertyKey<T> { private final Class<T> clazz; private final String name; public PropertyKey(Class<T> valueType, String name) { this.clazz = valueType; this.name = name; } public boolean checkType(Object value) { if (null == value) { return true; } return this.clazz.isAssignableFrom(value.getClass()); } ... rest of the class }
Then you create a data structure that uses it:
public class PropertyHolder { private final ImmutableMap<PropertyKey<?>, ?> storage; @SuppressWarnings("unchecked") public <T extends Serializable> T get(PropertyKey<T> key) { return (T) storage.get(key); } public <T> PropertyHolder put(PropertyKey<T> key, T value) { Preconditions.checkNotNull(key, "PropertyKey cannot be null"); Preconditions.checkNotNull(value, "Value for key %s is null", key); Preconditions.checkArgument(key.checkType(value), "Property \"%s\" was given " + "value of a wrong type \"%s\"", key, value);
I will miss a lot of unnecessary details here, please let me know if something is unclear.
source share