0

Actually i am implementing one program in which i am retrieving information from database and i am setting that info to One Object using setters and i just want to print that Object parameters without using system.out.println(object.getHeadCount());

I just want like if i am giving system.out.println(object); so using this code it should print data in Json format or any other readable format.

How to do it.Because my object is containing 30 fields so it is very hectic to write 30 getters to print data.

Parag Bhingre
  • 830
  • 2
  • 11
  • 20

4 Answers4

3

You have to override toString()

Normal way

class User {
    private String firstName;
    private String lastName;

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString(){
        return this.firstName + " " + this.lastName;
    }
}

Using Apache Commons

class User {
    private String firstName;
    private String lastName;

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString(){
        return new ToStringBuilder(this)
            .append("firstName", firstName)
            .append("lastName", lastName)
            .toString();
    }
}

Using Google Guava

class User {
    private String firstName;
    private String lastName;

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString(){
        return MoreObjects.toStringHelper(this)
            .add("firstName", firstName)
            .add("lastName", lastName)
            .toString();
    }
}
Tom
  • 16,842
  • 17
  • 45
  • 54
Damith Ganegoda
  • 4,100
  • 6
  • 37
  • 46
1

You simply have to override the toString() method of the class, read about it in java doc for Object class. Most IDE support it's automatic generation for all the fields of your class or for a number of them. Just for example:

class User {
    private String name;
    private String surname;

    User(String name, String surname)
    {
        this.name = name;
        this.surname = surname;
    }

    @Override
    public String toString()
    {
        return this.name+" "+this.surname;
    }
}
Stanislav
  • 27,441
  • 9
  • 87
  • 82
0

You should override toString() method. if you are using eclipse then you can try right-click within the editor, you'll find it under Source -> Generate toString()

soorapadman
  • 4,451
  • 7
  • 35
  • 47
0

To make a toString method you can simply just add one like so.

public String toString(){
    return "" + getValue();
}

The toString method is a part of

java.lang.Object

So it is implemented in every class.

Ryan
  • 1,972
  • 2
  • 23
  • 36