Parag Bhingre
Parag Bhingre

Reputation: 850

How to print contents of Java object without using getters

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.

Upvotes: 0

Views: 973

Answers (4)

Damith Ganegoda
Damith Ganegoda

Reputation: 4328

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();
    }
}

Upvotes: 3

Stanislav
Stanislav

Reputation: 28106

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;
    }
}

Upvotes: 1

Ryan
Ryan

Reputation: 1974

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.

Upvotes: 0

soorapadman
soorapadman

Reputation: 4509

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

Upvotes: 0

Related Questions