I have a generic class intended to keep values for different kinds of properties. I want to provide a type-safe way to set property values, so that it is impossible to assign property a value of wrong type.
I defined an interface to be implemented for all property kinds:
public interface Property<T> {
}
where type parameter T is used to specify the type of property value. Then assuming the class OrderProperty
implements this interface properties can be defined like
OrderProperty property1 = new OrderProperty<String>();
OrderProperty property2 = new OrderProperty<Integer>();
Initially I implemented the class to hold property values like
public class Properties<K extends Property> {
private Map<K, Object> properties = new HashMap<K, Object>();
public <V> void set(K key, V value) {
properties.put(key, value);
}
}
The problem is that the set() method is obviously not type-safe as it does not regard the connection between property and its value type so I could easily write something like
Properties orderProperties = new Properties<OrderProperty>();
OrderProperty countProperty = new OrderProperty<Integer>();
orderProperties.put(countProperty, "1");
and it would compile.
Type-safe implementation would be
public <V> void set(Property<V> key, V value) {
properties.put(key, value);
}
but of course it will not not compile since key is not of generic type.
I need something like
public <V> void set(K<V> key, V value) {
properties.put(key, value);
}
but this one is syntactically incorrect.
I am wondering if there is any way to get what I need.