I had a list with different implementations of the Field class which each had a form of a get... method. For instance the ExternalDecimalAsInt has a getInt method, while the StringField has getString. method. Both methods parse a byte stream and return the data. Since I'm writing Groovy, I don't care about the data type, I just wanted a simple way to invoke the get... method, regardless of the class type.
So I created a method reference in my object, and using a switch statement load the method reference according to the type of object that I'm dealing with.
class MyObject { def MethodClosure read //probably would omit the data type normally } private void generateReader(MyObject myObject, Field field) { switch (field) { case StringField: myObject.read = field.&getString break case IntAccessor: myObject.read = field.&getInt break case BigDecimalAccessor: myObject.read = field.&getBigDecimal break case LongAccessor: myObject.read = field.&getLong break case BigIntegerAccessor: myObject.read = field.&getBigInteger break } } //invokes getString, getInt, etc... depending on the object type def value = myObject.read(bytes)
Of course, you can always do the same thing with closures, but there's a little less syntax with the method references, and it looks cooler. Once I can use Java 8, I hear that method references are also more efficient than lamba expressions, the equivalent to Groovy closures.
case StringField: myObject.read = { field.getString() }
Post a Comment