t.vb.w
t.vb.w

Reputation: 117

How to add a string as part of a variable name representing an integer, java

I want to add a string to a variable name that represents an integer. For example:

String test = "v1f1";
set_view(R.drawable.test);

And then ideally it would look for R.drawable.v1f1, but it looks for R.drawable.test instead, which doesn't exist.

Anyone know how to do this?

Thanks.

Upvotes: 0

Views: 545

Answers (3)

Steve B.
Steve B.

Reputation: 57333

You could do this with an enum, as long as you limit yourself to values existing in the enum: e.g.

public enum Values {
    A,B,C,D;
}

String test = "A";
set_view(Values.valueOf(test));

You could even do it with integers it you were willing to be really evil-

int test=1;
set_view(values.valueOf(new String( ((char)(test+(int)'A')));

Upvotes: 1

froadie
froadie

Reputation: 83213

There isn't really any dynamic naming capability in Java. You can sometimes get around it by using keys into HashMaps, but I don't see a way to do that in your situation.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503924

You'd have to use reflection to do this - but it's not generally a good idea. Why do you want to do this? What values might you have, and could you change it to use a collection of some kind?

Upvotes: 1

Related Questions