{"id":901,"date":"2015-08-07T09:01:00","date_gmt":"2015-08-07T08:01:00","guid":{"rendered":"http:\/\/benjiweber.co.uk\/blog\/?p=901"},"modified":"2015-08-10T06:06:41","modified_gmt":"2015-08-10T05:06:41","slug":"anonymous-types-in-java","status":"publish","type":"post","link":"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/","title":{"rendered":"Anonymous Types in Java"},"content":{"rendered":"<p class=\"lead\">Java allows casting to an intersection of types, e.g. (Number &#038; Comparable)5. When combined with default methods on interfaces, it provides a way to combine behaviour from multiple types into a single type, without a named class or interface to combine them.<\/p>\n<p>Let&#8217;s say we have two interfaces that provide behaviour for Quack and Waddle.<\/p>\n<pre lang=\"java\">\r\ninterface Quacks {\r\n    default void quack() {\r\n        System.out.println(\"Quack\");\r\n    }\r\n}\r\ninterface Waddles {\r\n    default void waddle() {\r\n        System.out.println(\"Waddle\");\r\n    }\r\n}\r\n<\/pre>\n<p>If we wanted something that did both we&#8217;d normally declare a Duck type that combines them, something like <\/p>\n<pre lang=\"java\">\r\ninterface Duck extends Quacks, Waddles {}\r\n<\/pre>\n<p>However, casting to an intersection of types we can do something like <\/p>\n<pre lang=\"java\">\r\nwith((Anon & Quacks & Waddles)i->i, ducklike -> {\r\n    ducklike.quack();\r\n    ducklike.waddle();\r\n});\r\n<\/pre>\n<p>What&#8217;s going on here? Anon is a functional interface compatible with the identity lambda, so we can safely cast the identity lambda i->i to Anon.<\/p>\n<pre lang=\"java\">\r\ninterface Anon {\r\n    Object f(Object o);\r\n}\r\n<\/pre>\n<p>Since Quacks and Waddles are both interfaces with no abstract methods, we can also cast to those and there&#8217;s still only a single abstract method, which is compatible with our lambda expression. So the cast to (Anon &#038; Quacks &#038; Waddles) creates an anonymous type that can both quack() and waddle().<\/p>\n<p>The with() method is just a helper that also accepts a consumer of our anonymous type and makes it possible to use it.<\/p>\n<pre lang=\"java\">\r\nstatic <T extends Anon> void with(T t, Consumer<T> consumer) {\r\n    consumer.accept(t);\r\n}\r\n<\/pre>\n<p>This also works when calling a method that accepts an intersection type. We might have a method that accepts anything that quacks and waddles.<\/p>\n<pre lang=\"java\">\r\npublic static <Ducklike extends Quacks &#038; Waddles> void doDucklikeThings(Ducklike ducklike) {\r\n    ducklike.quack();\r\n    ducklike.waddle();\r\n}\r\n<\/pre>\n<p>We can now invoke the above method with an intersection cast<\/p>\n<pre lang=\"java\">\r\ndoDucklikeThings((Anon & Quacks & Waddles)i->i);\r\n<\/pre>\n<h2>Source code<\/h2>\n<p>You can find <a href=\"https:\/\/github.com\/benjiman\/java-anonymous-types\/\">complete examples on github<\/a><\/p>\n<h2>Enhancing existing objects<\/h2>\n<p>Some have asked whether one can use this to add functionality to existing objects. This trick only works with lambdas, but we can make use of a delegating lambda, for common types like List that we might want to enhance.<\/p>\n<p>Let&#8217;s say we are fed up of having to call list.stream().map(f).collect(toList()) and wish List had a map() method on it directly.<\/p>\n<p>We could do the following<\/p>\n<pre lang=\"java\">\r\nList<String> stringList = asList(\"alpha\",\"bravo\");\r\nwith((ForwardingList<String> & Mappable<String>)() -> stringList, list -> {\r\n    List<String> strings = list.map(String::toUpperCase);\r\n    strings.forEach(System.out::println);\r\n});\r\n<\/pre>\n<p>Where Mappable<String> declares our new method<\/p>\n<pre lang=\"java\">\r\ninterface Mappable<T> extends DelegatesTo<List<T>> {\r\n    default <R> List<R> map(Function<T,R> mapper) {\r\n        return delegate().stream().map(mapper).collect(Collectors.toList());\r\n    }\r\n}\r\n<\/pre>\n<p>And DelegatesTo<T> is a common ancestor with our ForwardingList <\/p>\n<pre lang=\"java\">\r\ninterface DelegatesTo<T> {\r\n    T delegate();\r\n}\r\ninterface ForwardingList<T> extends DelegatesTo<List<T>>, List<T> {\r\n    default int size() {\r\n        return delegate().size();\r\n    }\r\n    \/\/... and so on\r\n}\r\n<\/pre>\n<p><a href=\"https:\/\/github.com\/benjiman\/java-anonymous-types\/blob\/master\/src\/main\/java\/com\/benjiweber\/anonymous\/EnhancingListExample.java\">Here&#8217;s a full example<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Java allows casting to an intersection of types, e.g. (Number &#038; Comparable)5. When combined with default methods on interfaces, it provides a way to combine behaviour from multiple types into a single type, without a named class or interface to combine them. Let&#8217;s say we have two interfaces that provide behaviour for Quack and Waddle&#8230;.  <a href=\"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/\" class=\"more-link\" title=\"Read Anonymous Types in Java\">Read more &raquo;<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8],"tags":[],"class_list":["post-901","post","type-post","status-publish","format-standard","hentry","category-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Anonymous Types in Java - Benji&#039;s Blog<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Anonymous Types in Java - Benji&#039;s Blog\" \/>\n<meta property=\"og:description\" content=\"Java allows casting to an intersection of types, e.g. (Number &#038; Comparable)5. When combined with default methods on interfaces, it provides a way to combine behaviour from multiple types into a single type, without a named class or interface to combine them. Let&#8217;s say we have two interfaces that provide behaviour for Quack and Waddle.... Read more &raquo;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"Benji&#039;s Blog\" \/>\n<meta property=\"article:published_time\" content=\"2015-08-07T08:01:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2015-08-10T05:06:41+00:00\" \/>\n<meta name=\"author\" content=\"benji\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"benji\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/08\\\/07\\\/anonymous-types-in-java\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/08\\\/07\\\/anonymous-types-in-java\\\/\"},\"author\":{\"name\":\"benji\",\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/#\\\/schema\\\/person\\\/45ecb36b51f4ce99e6929d2d31ca5c09\"},\"headline\":\"Anonymous Types in Java\",\"datePublished\":\"2015-08-07T08:01:00+00:00\",\"dateModified\":\"2015-08-10T05:06:41+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/08\\\/07\\\/anonymous-types-in-java\\\/\"},\"wordCount\":330,\"commentCount\":2,\"articleSection\":[\"Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/08\\\/07\\\/anonymous-types-in-java\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/08\\\/07\\\/anonymous-types-in-java\\\/\",\"url\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/08\\\/07\\\/anonymous-types-in-java\\\/\",\"name\":\"Anonymous Types in Java - Benji&#039;s Blog\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/#website\"},\"datePublished\":\"2015-08-07T08:01:00+00:00\",\"dateModified\":\"2015-08-10T05:06:41+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/#\\\/schema\\\/person\\\/45ecb36b51f4ce99e6929d2d31ca5c09\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/08\\\/07\\\/anonymous-types-in-java\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/08\\\/07\\\/anonymous-types-in-java\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/2015\\\/08\\\/07\\\/anonymous-types-in-java\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Anonymous Types in Java\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/\",\"name\":\"Benji&#039;s Blog\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/#\\\/schema\\\/person\\\/45ecb36b51f4ce99e6929d2d31ca5c09\",\"name\":\"benji\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/417ada828fa4be09324820d24c0d93c3bfcbae183629e09117c9f4c4ab7ed43a?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/417ada828fa4be09324820d24c0d93c3bfcbae183629e09117c9f4c4ab7ed43a?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/417ada828fa4be09324820d24c0d93c3bfcbae183629e09117c9f4c4ab7ed43a?s=96&d=mm&r=g\",\"caption\":\"benji\"},\"sameAs\":[\"http:\\\/\\\/benjiweber.co.uk\"],\"url\":\"https:\\\/\\\/benjiweber.co.uk\\\/blog\\\/author\\\/benji\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Anonymous Types in Java - Benji&#039;s Blog","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/","og_locale":"en_US","og_type":"article","og_title":"Anonymous Types in Java - Benji&#039;s Blog","og_description":"Java allows casting to an intersection of types, e.g. (Number &#038; Comparable)5. When combined with default methods on interfaces, it provides a way to combine behaviour from multiple types into a single type, without a named class or interface to combine them. Let&#8217;s say we have two interfaces that provide behaviour for Quack and Waddle.... Read more &raquo;","og_url":"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/","og_site_name":"Benji&#039;s Blog","article_published_time":"2015-08-07T08:01:00+00:00","article_modified_time":"2015-08-10T05:06:41+00:00","author":"benji","twitter_card":"summary_large_image","twitter_misc":{"Written by":"benji","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/#article","isPartOf":{"@id":"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/"},"author":{"name":"benji","@id":"https:\/\/benjiweber.co.uk\/blog\/#\/schema\/person\/45ecb36b51f4ce99e6929d2d31ca5c09"},"headline":"Anonymous Types in Java","datePublished":"2015-08-07T08:01:00+00:00","dateModified":"2015-08-10T05:06:41+00:00","mainEntityOfPage":{"@id":"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/"},"wordCount":330,"commentCount":2,"articleSection":["Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/","url":"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/","name":"Anonymous Types in Java - Benji&#039;s Blog","isPartOf":{"@id":"https:\/\/benjiweber.co.uk\/blog\/#website"},"datePublished":"2015-08-07T08:01:00+00:00","dateModified":"2015-08-10T05:06:41+00:00","author":{"@id":"https:\/\/benjiweber.co.uk\/blog\/#\/schema\/person\/45ecb36b51f4ce99e6929d2d31ca5c09"},"breadcrumb":{"@id":"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/benjiweber.co.uk\/blog\/2015\/08\/07\/anonymous-types-in-java\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/benjiweber.co.uk\/blog\/"},{"@type":"ListItem","position":2,"name":"Anonymous Types in Java"}]},{"@type":"WebSite","@id":"https:\/\/benjiweber.co.uk\/blog\/#website","url":"https:\/\/benjiweber.co.uk\/blog\/","name":"Benji&#039;s Blog","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/benjiweber.co.uk\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/benjiweber.co.uk\/blog\/#\/schema\/person\/45ecb36b51f4ce99e6929d2d31ca5c09","name":"benji","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/417ada828fa4be09324820d24c0d93c3bfcbae183629e09117c9f4c4ab7ed43a?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/417ada828fa4be09324820d24c0d93c3bfcbae183629e09117c9f4c4ab7ed43a?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/417ada828fa4be09324820d24c0d93c3bfcbae183629e09117c9f4c4ab7ed43a?s=96&d=mm&r=g","caption":"benji"},"sameAs":["http:\/\/benjiweber.co.uk"],"url":"https:\/\/benjiweber.co.uk\/blog\/author\/benji\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/901","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/comments?post=901"}],"version-history":[{"count":7,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/901\/revisions"}],"predecessor-version":[{"id":908,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/901\/revisions\/908"}],"wp:attachment":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/media?parent=901"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/categories?post=901"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/tags?post=901"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}