DanielleC DanielleC - 10 months ago 32
Java Question

Java: how to parse a string in this situation?

So I have created a simple class in Java like this:

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

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

public void checkInfo

Is there a way to parse a string (property) in order to get Book properties like this, instead of doing

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

String property = "title";

Thanks in adance!


If you really want to access many properties as String, I suggest you using a Map<String, String> like this :

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

    public void setProperty(String name, String value)

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

Now you can use like this :

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"))