Tuesday, August 13, 2013

Enum: A safe translator


Many times we see an Enum declared like the following:


The Enum represents a value by Integer, and supplies a method (findByValue) to translate an int value to Enum value.

That is an error prone way to do that since every time you need to add/update/remove an Enum value you will need to remember to update 'findByValue' method

A possible fix

A better approach will be to do the following:


We keep a static HashMap that is statically initialized, and the 'findByValue' method is simpler. This version of the Enum makes sure any Enum value added/removed/updated will be automatically represented in the HashMap. i.e. no need for updating 'findByValue'

Generalizing the solution

First an interface class that defines a 'getValue' method:
And now a small class that basically wraps the HashMap and supplies an easy way for Enums to initialize:


And now wrapping all will give us the following:

Sunday, March 24, 2013


Java 7 nio - Examples

In this post I will demonstrate the work with major components in the NIO package.

Path

Path as its name implies is a representation of a system dependent file path.

Construct a Path by FileSystems:

Construct a Path by using the Paths utility class:



To list all files in a directory:


An example, create a folder Path and get data


An example, create a file Path and get data

Normalize a Path example


Working with sub Path