QueryStringBindable for a custom enum

enums, java, playframework, query-string

Solution

I had the same problem and I finally found out that it is not solvable as is.

By reading the documentation for `PathBindable` and `QueryStringBindable` I found that play framework requires the Bindable to provide a No Argument public constructor. Which by definition is no possible with `enum` in Java.

I'd like to offer you the same solution I gave another (more recent) question. I just wrapped the enum into a small Wrapper class that implements `QueryStringBindable` or `PathBindable`.

play framework - bind enum in routes

Problem

I've defined an enum type `Format` that implements `QueryStringBindable`. I think I've implemented it correctly, but in my routes file, I can't specify my type as a route parameter, because the compiler can't find it, and I have no idea how to import it into the routes file. Here's the enum: ``` package web; import java.util.Map; import play.libs.F; import play.mvc.QueryStringBindable; public enum Format implements QueryStringBindable<Format> { Html, Pdf, Csv; private Format value; @Override public F.Option<Format> bind(String key, Map<String, String[]> data) { String[] vs = data.get(key); if (vs != null && vs.length > 0) { String v = vs[0]; value = Enum.valueOf(Format.class, v); return F.Option.Some(value); } return F.Option.None(); } @Override public String unbind(String key) { return key + "=" + value; } @Override public String javascriptUnbind() { return value.toString(); } } ``` And here's my route: ``` GET /deposits controllers.Deposits.index(selectedAccountKey: Long ?= 0, format: Format ?= Format.Html) ``` How can I tell the compiler about my enum? Thanks! Edit I've also tried adding the path to the type in Build.scala as has been recommended in other posts: ``` val main = PlayProject(appName, appVersion, appDependencies, mainLang = JAVA).settings( routesImport += "web.Format", resolvers += Resolver.url("My GitHub Play Repository", url("http://www.joergviola.de/releases/"))(Resolver.ivyStylePatterns) ) ``` I changed that and restarted my server, but it appears to make no difference whatsoever.

Original source

Related problems