I am trying to design a generic Key class in java to represent primary pojo keys.
The values can be of various types i.e. BigInteger, String, Uuid’s . I am looking for best option to implement such a class. My current implementation looks something like this.
Can anyone help me with a more accurate implementation or identify issues with the current implementation? I am yet to implement a equals method. Any pointers are welcome.
This class needs to be GWT compatible.
@SuppressWarnings("serial")
@GwtCompatible
public class Key<T extends Serializable> implements Serializable {
public enum KeyType {
BigInt, Uuid, String ;
}
private final T keyValue ;
private final KeyType keyType ;
Key() {
keyValue = null;
keyType = null;
}
public Key(T value){
this.keyValue = value ;
this.keyType = determineKeyType(value);
}
/**
* @return
*/
private KeyType determineKeyType(Object value) {
if ( isValueUuid(value))
return KeyType.Uuid ;
else if (value instanceof BigInteger)
return KeyType.BigInt ;
else
return KeyType.String;
}
/**
* @param value
* @return
*/
private boolean isValueUuid(Object value) {
// TODO Auto-generated method stub
return false;
}
public Key(T val, KeyType tp){
this.keyValue = val ;
this.keyType = tp;
}
public KeyType getKeyType(){
return keyType ;
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
public T getKeyValue(){
return this.keyValue ;
}
}
It looks to me me that you would benefit from a Factory pattern here.
You would have an interface
Key, anAbstractKey, and as many implementations of thisAbstractKeyas you want (in your example case, it should be 3). The KeyFactory would be in charge of creating the key.Practically, it would give:
One advantage of this solution, even if it’s more verbose than the one you already have, is that you can restrict the types of your
Keys to what you actually need. In addition, with constructors that have limited visibility (just enough to make GWT compile properly), you can enforce the code to use theKeyFactory.