Clinton
Clinton

Reputation: 23135

How to make a class printable using Java/Groovy

Can I make a class printable (i.e. print(x) works) by overriding its toString() method, or is there some other way? toString() requires creating a string, which I imagine would involve a lot of wasted concatenation, particularly for nested structures.

It would seem to be more sensible if there was a print(PrintStream os) method available, but I couldn't find one.

Upvotes: 1

Views: 281

Answers (3)

Will
Will

Reputation: 14519

For non nested structures, dump() is a quick solution:

class Person { 
    String name
    String surname 
}

p = new Person(name: "John", surname: "Doe")
println p.dump()
// prints <Person@802ef9 name=John surname=Doe>

Upvotes: 0

dmahapatro
dmahapatro

Reputation: 50245

+1 @Jeff. You can also use @Canonical with @ToString annotation.

import groovy.transform.*

@ToString(includeNames=true, cache=true)
@Canonical class Test{
    String a
    int b
    Book book
}

@ToString(includeNames=true, cache=true)
@Canonical class Book{
    String name
}

Test test = new Test('A', 1, new Book("Groovy In Action"))

//Prints
//Test(a:A, b:1, book:Book(name:Groovy In Action))  

print test
println ""
System.out.print test

Upvotes: 2

Jeff Storey
Jeff Storey

Reputation: 57192

You could add a print method to metaclass of Object if you're using groovy, and something like

Object.metaClass.print = { printStream ->
    printStream.print(delegate)
}

Though it sounds like you might be worrying about an unnecessary problem. You can use a StringBuilder (or groovy's string interpolation) to reduce concatenation. You could also use groovy's @ToString AST to add a toString method and turn on caching so it only happens once.

Upvotes: 0

Related Questions