正如我的标题所述,我试图通过字符串动态引用对象的实例。由于我可能没有使用完全正确的技术术语,所以这里基本上是起始状态。:
MyClass instance123 = new MyClass();
String referer = "instance123";
我想要做什么,请通过String referer 引用对象 instance123 。
E.g:
callObjectByString(referer).anyMethodOfMyClass();
我通常称之为:
instance123.anyMethodOfMyClass();
我希望这有点可以理解和可能。我知道总有一种不同的编程方式我可以肯定地以某种方式解决这个问题,但我仍然想找到解决这个问题的方法!
答案 0 :(得分:1)
以下是人们在评论中使用的Map
:
Map<String, MyClass> myInstancesCollection = new HashMap<>();
MyClass instance123 = new MyClass();
String referer = "intance123";
myInstancesCollection.put(referer, instance123);
MyClass instance124 = new MyClass();
referer = "intance124";
myInstancesCollection.put(referer, instance124);
//later on...
myInstancesCollection.get("instance123"); // to retrieve the instance123 object
myInstancesCollection.get("instance124"); // to retrieve the instance124 object
答案 1 :(得分:0)
为什么不这样做?
在MyClass
内,您可以创建一个“id”字段,如下所示:
public MyClass{
private String id;
public MyClass(String id){
this.id = id;
}
public getID(){
return id;
}
}
然后呢,
String refer = "test";
MyClass test = MyClass("test");
if(test.getID().equals(refer)){
//do something with the object test
}
如果您有List
个对象:
ArrayList<MyClass> objs = new ArrayList<>();
objs.add(new MyClass("obj1"));
objs.add(new MyClass("obj2"));
objs.add(new MyClass("obj3"));
String refer = "obj2";
for(int i = 0; i < objs.size(); i++){
if(objs.get(i).getID().equals(refer)){
//do something with objs.get(i)
}
}