java - 通过字符串使用对象?

标签 java

如果我只得到字符串,是否可以使用对象?我有一个来自“学生”类的对象“约翰”。在类“学生”中是一个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/

相关文章:

JavaFX 图表、快照

java.lang.UnsatisfiedLinkError - 加载多个 lib 文件?

java - 非法访问 : this web application instance has been stopped already

java - 如何在 android 中将 C++ 回调作为按钮的单击处理程序传递?

java - 推土机映射内部类

java - EditText 控制框出现问题

java - 线程问题,无法更改外部 TextView 的值

java - 无法使用命令行编译 Android/Java 项目

java - 如何获取JVM运行时调用的类?

java - 数据格式自动转换为父子格式