Guava tips: MediaType

The MediaType class in Guava is a useful abstraction of MIME types, also known as “media type” or “content type”. It has a lot of predefined constants for the most common types, and it allows you to create new instances specifying either a precise type or a wildcard, using “*”.

Furthermore, it has the concept of “charset”, which makes it very useful when using it in web applications.

Finally, it has an overridden toString method which is compliant with the RFC 2045.

For instance:

assertEquals(MediaType.JPEG, MediaType.create("image", "jpeg"));
assertEquals("image/jpeg", MediaType.JPEG.toString());
assertEquals("text/plain; charset=utf-8", MediaType.PLAIN_TEXT_UTF_8.toString());

The various predefined media types include: