-1

Is it possible to construct an object given a string, toString() method, and the Class itself.

For example we have class Book.

class Book
{
   // ...

   String getTitle()
   {
      return title;
   }

   String getPubYear()
   {
      return pubYear;
   }

   void setTitle(String _title)
   {
      title = _title;
   }

   void setPubYear(String _pubYear)
   {
      pubYear = _pubYear;
   }

   public String toString(){
      return title+" "+pubYear;

   }
}

If we have the String:

"ExampleTitle 2017"

How can we create an instance of the class Book, with which has attribute:

title=ExampleTitle

pubyear=2017

We can do the following:

Book book = new Book();
String exampleString = "ExampleTitle 2017";
String[] parts = exampleString.split();
book.setTitle(parts[0]);
book.setPubYear(parts[1]);

But this is long winded. Is there a more automatic way to do this?

xenteros
  • 15,586
  • 12
  • 56
  • 91
user3809938
  • 1,114
  • 3
  • 16
  • 35
  • 4
    Why do you think it's long winded? I don't know how you'd expect an "automatic" solution to have any understand of what part of your string maps to what – tddmonkey Nov 10 '16 at 12:09
  • toString() is not meant to provide somethig parseable, and allowing recreating the object. If you want that, then use an XML or JSON marshaller/unmarshaller. Not toString(). – JB Nizet Nov 10 '16 at 12:11
  • Add a new constructor: `public Book(String title, String year) {...}`. I am not that sure if `String` is suited for `year`. – pzaenger Nov 10 '16 at 12:12

1 Answers1

2

You can add a new constructor:

public Book(String s) {
    String[] parts = s.split(" ");
    if (parts.length() == 1) {
        this.title = s;
    } else {
       this.title=parts[0];
       this.pubYear(Integer.parseInt(parts[1]));
    }
}

You should add NumberFormatException handling on your own but I recommend my post about it.

The above constructor will take a String, split it by a space and perform what you have done. You can use it like:

Book book = new Book("Example_title 2001");

but it's not the best approach. You should rather use standard patterns and first extract the values you want to set to your Book and then pass them to the constructor.

The good way of doing what you want will be to make another constructor:

public class Book {

    public Book(String s, int y) {
        this.title = s;
        this.year = y;
    }
}

Please change year field to int or long. Year shouldn't be a String as long as you're not using Roman numbers.

Community
  • 1
  • 1
xenteros
  • 15,586
  • 12
  • 56
  • 91