0

This could sound strange but actually is quite simple.

Short description: I have a class variable called

public static final String ACCELEROMETER_X = "AccX";

In one function I do this, which get me "ACCELEROMETER_X" from a enum (sensors is an arrayList of my enum).

for i...
    columns = columns + sensors.get(i).name()

The point is I want to introduce in columns not "ACCELEROMETER_X", but "AccX". Any idea? I know I could do it using switch and cases but my enum has more than 30 values so Id rather prefer other "cleaner" way to do it.

2
  • Please provide more information on what you want to accomplish and what you are doing in your loop. Commented Jul 27, 2013 at 11:48
  • Once you realise that an enum is just syntactic sugar for a class, as Rohit has shown, then it all becomes easy. Commented Jul 27, 2013 at 11:57

4 Answers 4

1

If you want your enum constant to be replaced with that string value, a better way would be keep that string as a field in the enum itself:

enum Sensor {
    ACCELEROMETER_X("AccX"),
    // Other constants
    ;

    private final String abbreviation;

    private Sensor(final String abbreviation) {
        this.abbreviation = abbreviation;
    }

    @Override
    public String toString() {
        return abbreviation;
    }
}

And instead of:

sensors.get(i).name()

use this:

sensors.get(i).toString()
Sign up to request clarification or add additional context in comments.

Comments

0

Solution 1 : If you keep the value in class

Create a Map with key as the id (ACCELEROMETER_X) and value as "AccX" and when you get the value from the Enum use that to find the value from the map using name() as the key.

Map<String, String> map = new HashMap<String,String>();

map.put("ACCELEROMETER_X","AccX");

//some place where you want value from name
map.get(enumInstance.name());

Solution 2: Change the enum (more preferable)

enum Some{

   ACCELEROMETER_X("AccX");

}

Comments

0

In your enum add this

public String getAccelerometerX (){
    return ACCELEROMETER_X ;
}

and then:

for i... columns = columns + sensors.get(i).getAccelerometerX ()

Comments

0

I think what you're trying to do is to get the value of a field from its name which you have in a String, if that's the case, you could do something like this:

public static final String ACCELEROMETER_X = "AccX";

// ...

Field field = MyClassName.class.getField("ACCELEROMETER_X");
String value = (String)field.get(new MyClassName());

System.out.println(value); // prints "AccX"

Of course you'll have to catch some Exceptions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.