Vassilis De
Vassilis De

Reputation: 373

How to override toString() inside wrapper class?

I was shown a way to parse some data from a database to an entity. I was given this good wrapper class

public class ObjectWrapper implements Wrapper{
   private Object wrappedObject;
//...
public static Wrapper wrap(ResultSet rs, int column, int columnType) throws SQLException {        
        if (columnType == 0) {
            return new EmptyListExceptionWrapper();
        } else {
            return new ObjectWrapper(rs.getObject(column));
        }
    }
}

When I try to use it in order to parse those objects, I get the names like databaseConnection.ObjectWrapper@5010be6 and not as they really are. Another good fellow told me that I have to override toString() method inside ObjectWrapper class in order to get the real results.

How am I supposed to do that? I know that those primitive types cannot be added or changed. For example, should I do something like that below?

 public static String toString(){
     String str = new String();
     return str += wrappedObject;
 }

Upvotes: 1

Views: 1052

Answers (2)

Cheruvian
Cheruvian

Reputation: 5877

Object.toString() which is what your are calling in

str += wrappedObject;

will by default return the object's hashcode. You need to cast the wrappedObject to something that you can then print properties of

class objectDef{
    private int x;
    public int y;
    public int getX() { return x; }
}

//ToString method
public String toString()
{
    return "ObjectWrapper has Y: " + ((objectDef)wrappedObject).y) + " x: " + ((objectDef)wrappedObject).getX() ".";
}

Upvotes: 1

First, methods that apply to a specific instance of your class shouldn't be static, and you should generally avoid string concatenation in favor of a StringBuilder.

Second, a number of tools will create useful toString methods for you: your IDE can generate one, and Apache Commons Lang has ToStringBuilder.

If you don't have any information about the wrapped type (and its own toString implementation), then you might just use something like this:

@Override
public String toString() {
    // uses a StringBuilder implicitly
    return "ObjectWrapper[" + wrappedObject.toString() + "]";
}

Upvotes: 4

Related Questions