Skip to main content


Showing posts from September, 2013

instanceof operator and Visitor pattern replacement in Java 8

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 downcastingavoids instanceofclean and easy to usestrongly typedworks with classes that we have no control over, including JDK This small utility was developed with Akka and Java API in mind to limit the usage of instanceof op…