Peter Boomsma
Peter Boomsma

Reputation: 9836

Why can't I convert a object to string?

I'm trying to save an object into a database table but when the record is saved the name value is empty. I'm using Spring and Hibernate.

When I log the object in the MovieController:

@RequestMapping(value = "/", method = RequestMethod.POST)
public Movie createMovie(@RequestBody Movie movie){
    System.out.println(movie.toString());
    return movieService.createMovie(movie);
}

I see this value being logged.

com.movieseat.models.Movie@abee456

What I would expect is

id: 20, name: Star Wars

In my app.component.ts I have:

createMovie(movie: Movie): void {
  this._dataService.createMovie<Movie>({'id': 20, 'name': 'Star Wars'})
  .subscribe((data) => this.movie = data,
  error => () => {
      'something went wrong';
  },
  () => {
      console.log(this.movies);
  });
}

The app.service.ts

public createMovie<T>(movie: Movie): Observable<T> {
    console.log(movie);
    return this.http.post<T>('/api/movies/', movie);
}

So why is the System out returning the object and not the values in the object? Or at least I think that's what it's doing.

Upvotes: 0

Views: 770

Answers (2)

Robert H
Robert H

Reputation: 11730

Overridding toString is fairly easy. You can use your IDE to generate the code automatically, or just write it out.

In your example something like this may be all you need:

@Override
public String toString(){
    return "id: " + id + "name: " + name;
} 

Essentially what you're doing is the same thing you would do with System.out.println to print out the values of the object, only in this case the toString method provides a default handler on what properties you want printed so you don't need to specify them each time. Functionally this is equivalent to doing

System.out.println("id: " + movie.getId() + "name: " + movie.getName());

but, as you're likely to call the same print statement multiple times, it would become a pain to update each print statement to add a new parameter called Description.

At any rate - it's a best practice to override toString to print out your object for a variety of reasons (all subject to much discussion), but primarily it has helped me with debugging, as you're finding out first hand.

Upvotes: 2

Carlos Ch&#225;vez
Carlos Ch&#225;vez

Reputation: 432

Go to Movie.java and generate the toString method.

I suggest you make use of your IDE's features to generate it. Don't hand-code it.

if you are using Intellij press ALT + Insert and generate toString then try with

System.out.println(movie);

Upvotes: 0

Related Questions