{"id":569,"date":"2014-05-08T20:56:23","date_gmt":"2014-05-08T19:56:23","guid":{"rendered":"http:\/\/benjiweber.co.uk\/blog\/?p=569"},"modified":"2014-05-08T20:56:23","modified_gmt":"2014-05-08T19:56:23","slug":"json-to-java-interfaces-with-nashorn","status":"publish","type":"post","link":"https:\/\/benjiweber.co.uk\/blog\/2014\/05\/08\/json-to-java-interfaces-with-nashorn\/","title":{"rendered":"JSON to Java Interfaces with Nashorn"},"content":{"rendered":"<p class=\"lead\">Here&#8217;s a neat trick to transform JSON into Java objects that implement an interface with the same structure.<\/p>\n<p>Java 8 comes with Nashorn &#8211; a JavaScript runtime that has a number of <a href=\"https:\/\/wiki.openjdk.java.net\/display\/Nashorn\/Nashorn+extensions\">extensions<\/a>. <\/p>\n<p>One of these extensions allows you to pass a JavaScript object to a constructor of an interface to anonymously implement that interface. So for example we can do <\/p>\n<pre lang=\"javascript\">\r\njjs> var r = new java.lang.Runnable({ run: function() print('hello') });\r\njjs> r.run();\r\nhello\r\n<\/pre>\n<p>n.b. the above uses a JavaScript 1.8 lambda expression, which is supported by Nashorn and allows us to omit the braces and &#8220;return&#8221; keyword in the function defintion. We could have also omitted the parentheses in the Runnable constructor call in this case.<\/p>\n<p>Now let&#8217;s suppose we have a JSON file as follows <\/p>\n<pre lang=\"javascript\">\r\n{\r\n  \"firstname\":\"Some\",\r\n  \"lastname\":\"One\",\r\n  \"petNames\":[\"Fluffy\",\"Pickle\"],\r\n  \"favouriteNumber\":5\r\n}\r\n<\/pre>\n<p>and we want to to treat it as a Java interface as follows.<\/p>\n<pre lang=\"java\">\r\npublic interface Person {\r\n  String firstname();\r\n  String lastname();\r\n  List<String> petNames();\r\n  int favouriteNumber();\r\n} \r\n<\/pre>\n<p>It&#8217;s trivial to convert the JSON to a JavaScript object with JSON.parse.<\/p>\n<p>The only conceptual difference between the JavaScript object and the Java Interface is that in the interface the properties such as firstname and lastname are methods not literal strings. It&#8217;s easy to convert a JavaScript object such that each value is wrapped in a function definition.<\/p>\n<p>We just need to define a function that iterates through each value on our JavaScript object and wraps each in a function.<\/p>\n<pre lang=\"javascript\">\r\n\/\/ A function that takes a value and returns a function \r\n\/\/ which when invoked returns the original value\r\nfunction createFunc(value) function() value \r\n\/\/ Wrap each property in a function\r\nfunction iface(map) {\r\n  var ifaceImpl = {}\r\n  for (key in map) ifaceImpl[key] = createFunc(map[key]);\r\n  return ifaceImpl;\r\n}\r\n<\/pre>\n<p>Applying it to our JS object gives us the following<\/p>\n<pre lang=\"javascript\">\r\n{\r\n  \"firstname\":function() \"Some\",\r\n  \"lastname\":function() \"One\",\r\n  \"petNames\":function() [\"Fluffy\",\"Pickle\"],\r\n  \"favouriteNumber\":function() 5\r\n}\r\n<\/pre>\n<p>This is now satisfies our Java Interface, so we can just pass it to the constructor. Putting it all together<\/p>\n<pre lang=\"javascript\">\r\nvar Person = Packages.Person; \/\/ Import Java Person Interface\r\nvar someoneElse = new Person(iface({ \r\n  \"firstname\":\"Some\",\r\n  \"lastname\":\"One\",\r\n  \"petNames\":[\"Fluffy\",\"Pickle\"],\r\n  \"favouriteNumber\":5\r\n}));\r\n\r\nPerson.print(someoneElse); \/\/ Pass to a Java method that accepts a Person instance.\r\n<\/pre>\n<p>If our JSON were originally in a text file we could use Nashorn&#8217;s scripting extensions to read the text file and convert it to an interface in the same way. This can be useful for bootstrapping a Java app without a main method &#8211; you can read a JSON config file, convert it to a typed Java interface, and start the app. This can free the Java app from dealing with JSON or argument parsing<\/p>\n<pre lang=\"javascript\">\r\n#!\/usr\/bin\/jjs\r\nfunction createFunc(value) function() value\r\nfunction iface(map) {\r\n  var ifaceImpl = {}\r\n  for (key in map) ifaceImpl[key] = createFunc(map[key]);\r\n  return ifaceImpl;\r\n}\r\nvar Settings = Packages.Settings;\r\nvar MyApplication = Packages.MyApplication;\r\n\r\n\/\/ Backticks in Nashorn scripting mode works like in Bash\r\nvar settings = new Settings(iface(JSON.parse(`cat app_config.json`))); \r\nMyApplication.start(settings);\r\n<\/pre>\n<pre lang=\"java\">\r\npublic interface Settings {\r\n  String hostname();\r\n  int maxThreads();\r\n}\r\npublic class MyApplication {\r\n  public static void start(Settings settings) {\r\n    \/\/\r\n  }\r\n}\r\n<\/pre>\n<p>One small annoyance with this is that jjs (Nashorn executable) does not seem able to accept a classpath parameter when used with a shebang #!\/usr\/bin\/jjs . So for now you have to execute the JavaScript with <\/p>\n<pre lang=\"bash\">\r\n$ jjs -scripting -cp . .\/example.js\r\n<\/pre>\n<p>There&#8217;s a <a href=\"https:\/\/github.com\/benjiman\/JsonToInterface\">complete example here<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Here&#8217;s a neat trick to transform JSON into Java objects that implement an interface with the same structure. Java 8 comes with Nashorn &#8211; a JavaScript runtime that has a number of extensions. One of these extensions allows you to pass a JavaScript object to a constructor of an interface to anonymously implement that interface&#8230;.  <a href=\"https:\/\/benjiweber.co.uk\/blog\/2014\/05\/08\/json-to-java-interfaces-with-nashorn\/\" class=\"more-link\" title=\"Read JSON to Java Interfaces with Nashorn\">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":[],"categories":[8,26],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v14.9 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\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\/2014\/05\/08\/json-to-java-interfaces-with-nashorn\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"JSON to Java Interfaces with Nashorn - Benji&#039;s Blog\" \/>\n<meta property=\"og:description\" content=\"Here&#8217;s a neat trick to transform JSON into Java objects that implement an interface with the same structure. Java 8 comes with Nashorn &#8211; a JavaScript runtime that has a number of extensions. One of these extensions allows you to pass a JavaScript object to a constructor of an interface to anonymously implement that interface.... Read more &raquo;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/benjiweber.co.uk\/blog\/2014\/05\/08\/json-to-java-interfaces-with-nashorn\/\" \/>\n<meta property=\"og:site_name\" content=\"Benji&#039;s Blog\" \/>\n<meta property=\"article:published_time\" content=\"2014-05-08T19:56:23+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@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\":\"https:\/\/benjiweber.co.uk\/blog\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/2014\/05\/08\/json-to-java-interfaces-with-nashorn\/#webpage\",\"url\":\"https:\/\/benjiweber.co.uk\/blog\/2014\/05\/08\/json-to-java-interfaces-with-nashorn\/\",\"name\":\"JSON to Java Interfaces with Nashorn - Benji&#039;s Blog\",\"isPartOf\":{\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#website\"},\"datePublished\":\"2014-05-08T19:56:23+00:00\",\"dateModified\":\"2014-05-08T19:56:23+00:00\",\"author\":{\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#\/schema\/person\/45ecb36b51f4ce99e6929d2d31ca5c09\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/benjiweber.co.uk\/blog\/2014\/05\/08\/json-to-java-interfaces-with-nashorn\/\"]}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#\/schema\/person\/45ecb36b51f4ce99e6929d2d31ca5c09\",\"name\":\"benji\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/benjiweber.co.uk\/blog\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/05fb47b31a0b329e1b790074a9b624ef?s=96&d=mm&r=g\",\"caption\":\"benji\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","amp_enabled":true,"_links":{"self":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/569"}],"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=569"}],"version-history":[{"count":6,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/569\/revisions"}],"predecessor-version":[{"id":575,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/posts\/569\/revisions\/575"}],"wp:attachment":[{"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/media?parent=569"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/categories?post=569"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/benjiweber.co.uk\/blog\/wp-json\/wp\/v2\/tags?post=569"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}