简体   繁体   English

如何使用Java / Groovy使类可打印

[英]How to make a class printable using Java/Groovy

Can I make a class printable (ie print(x) works) by overriding its toString() method, or is there some other way? 我可以通过重写类的toString()方法使它成为可打印的类(即print(x)起作用),还是有其他方法? toString() requires creating a string, which I imagine would involve a lot of wasted concatenation, particularly for nested structures. toString()需要创建一个字符串,我想这会涉及很多浪费的串联,尤其是对于嵌套结构。

It would seem to be more sensible if there was a print(PrintStream os) method available, but I couldn't find one. 如果有可用的print(PrintStream os)方法似乎更明智,但我找不到。

+1 @Jeff. +1 @杰夫。 You can also use @Canonical with @ToString annotation. 您也可以将@Canonical与@ToString注释一起使用。

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

You could add a print method to metaclass of Object if you're using groovy, and something like 如果您使用的是groovy,则可以将print方法添加到Object元类中,例如

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. 您可以使用StringBuilder (或groovy的字符串插值)来减少串联。 You could also use groovy's @ToString AST to add a toString method and turn on caching so it only happens once. 您还可以使用groovy的@ToString AST添加toString方法并打开缓存,因此它只发生一次。

For non nested structures, dump() is a quick solution: 对于非嵌套结构, dump()是一个快速的解决方案:

class Person { 
    String name
    String surname 
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM