如何在 Java 中使用字符串指定名称?
String VARIABLE = "name";
Something VARIABLE = new Something();
有什么可能的方法我可以做这样的事情吗?
如何在 Java 中使用字符串指定名称?
String VARIABLE = "name";
Something VARIABLE = new Something();
有什么可能的方法我可以做这样的事情吗?
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"));