Skip to content

Printing the enum’s name

I’m using eclipse + Android SDK on Ubuntu.

I would like to print the name of a sensor type device, there a a lot of them and I want to do it automatically.

If I use a

Log.d("SENSORTYPE","Type: " + tempSensor.getType())

I print the (int) type, but I would like the name of the enum.

How could I do that?



For enumerations, you can obtain an array of all the constants and loop over them very easily using code such as this:

for(YourEnum value: YourEnum.values()){

However, the Sensor class you link to isn’t an enumeration, but contains a list of constants. There’s no way to programatically loop over that list like an enumeration without specifying all the constants names.

However, you can create a static lookup that maps the ints to the String value you want to use, for example

Map<Integer,String> lookup = new HashMap<Integer,String>();
//Code a put for each TYPE, with the string you want to use as the name

You can use this like this:

Log.d("SENSORTYPE","Type: " + lookup.get(tempSensor.getType()));

This approach does mean you still have to write out each constant and update the list if the constants change, but you only have to do it once. It’d be a good idea to wrap the lookup in some kind of helper method or class depending on how widely you want to reuse it.

9 People found this is helpful