简体   繁体   中英

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.

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM