السبت، 6 أغسطس 2005

Generics and Parameters of Type Class

Generics allow parameters to determine the type of the return value. This can be used to avoid a cast when returning objects from an internal map, by using the class of the object as a key. Note that put() also enforces the type of the value, at compile time.
public class TypedMap {
private Map _data = new HashMap();
public T get(Class key) {
return key.cast(_data.get(key));
}
public void put(Class key, T value) {
_data.put(key, value);
}
public static void main(String[] args) {
TypedMap typedMap = new TypedMap();
typedMap.put(Integer.class, new Integer(3)); // could also auto-box here
Integer myInt = typedMap.get(Integer.class); // could also auto-unbox here
}
}
If you need several keys whose value has the same class, you can extend the above idea as follows. If you want different keys with the same content to point to the same value, you'll have to implement equals() and hashCode(), though.
public class TypedMap2 {
public static class Key {
public String id;
public Class contentType;
protected Key(String myID, Class myContentType) {
id = myID;
contentType = myContentType;
}
}
/** pre-defined keys */
public static final Key INT_KEY = new Key("intKey", Integer.class);

private Map _data = new HashMap();
public T get(Key key) {
return key.contentType.cast(_data.get(key));
}
public void put(Key key, T value) {
_data.put(key, value);
}
public static void main(String[] args) {
TypedMap2 typedMap = new TypedMap2();
typedMap.put(INT_KEY, new Integer(3)); // could also auto-box here
Integer myInt = typedMap.get(INT_KEY); // could also auto-unbox here
}
}