Java 使用字符串值作为变量名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20974558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:39:23  来源:igfitidea点击:

To use a string value as a variable name

java

提问by julian

Is it possible to use String as a variable name.. like in this example -

是否可以使用 String 作为变量名.. 就像在这个例子中 -

String musicPlaying = "music2";
Music music1 = new Music("blaalla");
Music music2 = new Music("blalala");
Music music3 = new Music("balaada");

if(!musicPlaying.stillPlaying) { // As you can see i am using string as a variable name.
  changeMusic();
}

采纳答案by Wins

What you can do is by associating (mapping) those values to the Music object. Here is example:

您可以做的是将这些值关联(映射)到 Music 对象。这是示例:

Map<String, Music> musics = new HashMap<>();
String musicPlaying = "music2";
musics.put("music1", new Music("blaalla"));
musics.put("music2", new Music("blalala"));
musics.put("music3", new Music("balaada"));

if(!musics.get(musicPlaying).stillPlaying) { // As you can see i am using string as a variable name.
  changeMusic();
}

回答by david99world

No, this is not supported in Java.

不,这在 Java 中不受支持。

stillPlayingdoesn't exist as a method (or variable) on String.

stillPlaying不作为方法(或变量)存在String

As the comment suggests below, it probably is doable through some reflection, however to quote another comment...

正如下面的评论所暗示的那样,通过一些反思可能是可行的,但是引用另一条评论......

You can do all kinds of stupid tricks with reflection. But you're basically breaking the "warranty void if removed" sticker on the class the instant you do it.

你可以用反射做各种愚蠢的把戏。但是你基本上打破了课堂上的“如果被移除则保修无效”的标签。

回答by Kevin Workman

No. But you might want to look into using a Map instead.

不,但您可能想考虑使用 Map 代替。

回答by Silviu Burcea

You can't do this in Java, but you can almost do it using a map.

你不能在 Java 中做到这一点,但你几乎可以使用地图来做到这一点。

Map<String, Music> map = new HashMap<String, Music>();
map.put("music1", music1);
map.put("music2", music2);
map.put("music3", music3);

if(map.get(musicPlaying).stillPlaying) {
  // happy listening 
}

回答by rupweb

I used a switch case.

我用了一个开关盒。

Switch (string)
{
    case "string1":
    string1();
    break;
    case "string2":
    string2();
    break;
}