I just learnt something great about generics and thought I’d share it.
We have several systems that take care of persistence and caching, which usually involve getting hold of a store through a factory method something like this
public static <K extends Serializable, V extends Serializable> Store<K, V>
getInstance(String name, Class keyClass, Class valueClass)
Up until now, I was very frustrated that there was no way to check that the Class parameters are actually related to the generic types K and V, and I had to explicitly check they extended Serializable.
But it turns out that the Class object itself can have a generic type K forced upon it. For example Class<List> will only accept the class of an object that implements List. The method then becomes
public static <K extends Serializable, V extends Serializable> Store<K, V>
getInstance(String name, Class<K> keyClass, Class<V> valueClass)
and suddenly things become a lot cleaner… specifically there is no need to check that the Classes are subclasses of Serializable or that generic objects can be cast to one of the Class parameters in every set method. That said, it would be much better to be able to lose the Class parameters altogether and allow runtime access of generic types, but unfortunately Java’s legacy fails us there.
Oh, and while I have you in generic mode, isn’t the “Type mismatch” error here just the most annoying thing ever?
List<Object> stooges = Arrays.asList("Larry", "Moe", "Curly");
We all know it is perfectly fine to go and do thisList<Object> stooges = new ArrayList();
stooges.add("Larry");
stooges.add("Moe");
stooges.add("Curly");
A correction is to do
List<? extends Object> stooges = Arrays.asList("Larry", "Moe", "Curly");
but having to explicitly say the type extends is just annoying. Does anyone know of a valid case where it would be bad to allow a sub-type to be assigned in place of a type?
Ricky Clarkson wrote:
April 28th, 2007 at 3:40 pm