Skip to main content

Posts

Showing posts from September, 2013

instanceof operator and Visitor pattern replacement in Java 8

Bridge to Ulvøya I had a dream where instanceof operator and downcasting were no longer needed but without clumsiness and verbosity of visitor pattern . So I came up with the following DSL syntax: Object msg = //... whenTypeOf(msg). is(Date.class). then(date -> println(date.getTime())). is(String.class). then(str -> println(str.length())). is(Number.class). then(num -> println(num.intValue())). orElse(obj -> println("Unknown " + obj)); No downcasting, clean syntax, strong-typed and... perfectly achievable in Java 8. Using lambdas and a little bit of generics I created a tiny library called typeof that is clean, easy to use and more robust than instanceof and Visitor pattern taken together. Advantages include: no explicit downcasting avoids instanceof clean and easy to use strongly typed works with classes that we have no control over, including JDK This small utility was developed with Akka and Java API i