您要查找的内容称为“变量变量”。 Java 不支持这些,但某些语言like PHP 支持。但是,您可以使用生成的键创建对象的 HashMap,如下所示:
Map<String, Object> map = new HashMap<String, Object>;
// makes a HashMap of strings to objects;
// if you want to use something else for the keys,
// you can change the first type name between the <>
map.put("key", object);
//adds an object to the HashMap for the key "key"
然后像这样从地图中取回对象:
map.get("key");
//will return object
如果您想在 for 循环中执行此操作,您可以执行以下操作:
Map<String, Object> map = new HashMap<String, Object>;
String[] keys = {"foo", "bar", "food", "bard", "fooley", "barley"};
for(int i = 0; i < keys.length; i++) {
map.put(keys[i], myObject);
}
This answer 是一种随机生成这些字符串的方法。