Rafag
Rafag

Reputation: 729

How to get an String value from another String

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.

Upvotes: 0

Views: 105

Answers (4)

Rohit Jain
Rohit Jain

Reputation: 213213

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()

Upvotes: 1

morgano
morgano

Reputation: 17422

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.

Upvotes: 0

M-Wajeeh
M-Wajeeh

Reputation: 17284

In your enum add this

public String getAccelerometerX (){
    return ACCELEROMETER_X ;
}

and then:

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

Upvotes: 0

Narendra Pathai
Narendra Pathai

Reputation: 41935

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");

}

Upvotes: 0

Related Questions