gpt4 book ai didi

Java:在这种情况下如何解析字符串?

转载 作者:行者123 更新时间:2023-12-01 16:52:31 25 4
gpt4 key购买 nike

所以我用 Java 创建了一个简单的类,如下所示:

public class Book {
private String author;
private String title;

public Book (String author, String title) {
this.author = author;
this.title = title;
}
}

public void checkInfo

有没有办法解析字符串(属性)以获得像这样的 Book 属性,而不是执行 bookA.title

Book bookA = new Book("George Orwell","Animal Farm")

String property = "title";
System.out.print(bookA.property);

提前致谢!

最佳答案

如果您确实想访问 String 等许多属性,我建议您使用Map<String, String>像这样:

public class Book
{
private Map<String, String> properties = new HashMap();

public void setProperty(String name, String value)
{
properties.set(name,string);
}

public String getProperty(String name)
{
return properties.get(name);
}
}

现在你可以像这样使用:

Book book = new Book();

book.setProperty("title","Animal Farm");
book.setProperty("author","George Orwell");

System.out.println("Book: " + book.getProperty("title") + " by " + book.getProperty("author"))

关于Java:在这种情况下如何解析字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37233764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com