Java 8 default method and REST

If you are following new Java features coming with each version, you certainly did not miss the default methods introduced with Java SE 8. This new language construct gives you the ability to define the default method implementation directly in the interface. If the (non-abstract) subclass does not create its own implementation, the default method in the interface is called.

The syntax is pretty easy:

Why would I do that?

Why is that useful? Isn’t it just another syntactic sugar? You can simply achieve something very similar using abstract class after all… Well, not always. The new syntax can be very useful if you have to change your public API after while. It makes it possible to add a method to your interface while still be backwards compatible, in other words without breaking someone’s code.

REST it up!

Most of developers already did know all that stuff, but have you actually tried to use some nice annotations to transform that interface into a fully functional JAX-RS resource (of course along with the – possibly empty – concrete class)?

I didn’t, until recently! And you know what? It just works. Let’s create a little example.

Of course, this is still an interface and as such, it cannot be instantiated. In order to create a functional JAX-RS resource, you need to implement it:

Now register the resource as you would normally do, in this case in a servlet-3 container (just for the sake of diversity, it will work with grizzly as well):

and you are done. No deployment descriptor and servlet registration needed, the @ApplicationPath annotation takes care of it. Just remember not to register the interface separately, Jersey tries to instantiate the root resource classes and that would not succeed of course.

Your resource suddenly has three resource methods and from the API user’s point of view, there is no difference against a “conventional” resource class.

If you look at the WADL ([applications-base-URI]/application.wadl), you won’t see anything suspicious either:

Just don’t forget to build with Java 8.

Example app can be found on GitHub.

By the way, another Java 8 feature – support for Optional is coming soon to Jersey as well, so stay tuned!




Leave a Reply

Your email address will not be published. Required fields are marked *