DanielleC DanielleC - 6 months ago 9
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
bookA.title
?

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

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


Thanks in adance!

Answer

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)
    {
        properties.set(name,string);
    }

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