如果我只得到字符串,是否可以使用对象?我有一个来自“学生”类的对象“约翰”。在类“学生”中是一个ArrayList“ friend ”。我想通过使用字符串(对象的名称)来访问对象“John”。 (示例中的第 2 行)
public void addFriend(Student student, String friend) throws IOException{
student.friends.add(friend);
System.out.println("Friend: " + friend + " added to List of " + student);
}
我希望你明白我的意思(我很抱歉我糟糕的英语:/)
最佳答案
您可以使用 map 来解决此问题。
Map<String, Student> friends = new HashMap<String, Student>();
friends.put("John", objectOfJohn);
Student target = friends.get("John");
关于java - 通过字符串使用对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38165795/