-1

如何在 Java 中使用字符串指定名称?

String VARIABLE = "name";

Something VARIABLE = new Something();

有什么可能的方法我可以做这样的事情吗?

4

1 回答 1

2

Basically I want to name a variable using the value of a String.

You can't do that. Names of variables need to be know at compilation-time to let compiler do its work, not at run-time. What is more, after compilation variables doesn't have names.

If you are searching for something like key->value mapping where key can be dynamically created String, and instance of Something will be values you can use Map<String,Something>.

Example:

Map<String,Something> map = new HashMap<>();
//lets put our pair in map 
map.put("name", new Something());
//lets print value stored in `name` key
System.out.println(map.get("name"));
于 2014-12-29T00:22:03.863 回答