将对象信息打印为 toString() 而不使用 toString()?
我的问题是,是否可以从 JAVA 中不提供 toString() 方法的类中打印出特定信息?
问题是:我们为我们的应用程序提供了一个记录器(使用aspectJ),它打印出给出的特定参数。例如:
public void addGroupMembers(Group group, String doneBy, DataListModel<User> users) {
doSomething()
}
我们的 Logger 打印以下内容:
addGroupMembers called with given arguments:
Group = [id = ..... and so on]
username
DataListModel$1231 <-
我们必须使用 DataListModel-Class,因为我们在后台使用 JSF。但是,正如您所看到的,此类不提供 toString 方法。
我们的记录器是我们自己编写的,因此我们可以对其进行调整。是否可以模拟 toString 方法,例如:如果类不提供 toString,则捕获其所有字段并打印它们?
或者还有其他办法吗?
预先感谢您的帮助。 你好,雷钩
my Question is, is it possible to print out specific information from a class that provides no toString() method in JAVA?
There's the rub: We provide a logger for our application (using aspectJ) which prints out the specific arguments, that were given. For example:
public void addGroupMembers(Group group, String doneBy, DataListModel<User> users) {
doSomething()
}
And our Logger prints the following:
addGroupMembers called with given arguments:
Group = [id = ..... and so on]
username
DataListModel$1231 <-
We have to use the DataListModel-Class, because we're working with JSF in the background. But, as you can see, this class doesn't provide a toString method.
Our logger is written by ourself, so we can adapt that. Is it possible to simulate a toString method like: If the class doesn't provide a toString, catch all their fields, and print them?
Or is there any other way?
Thanks in advance for your help.
Greetings, Thunderhook
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 ReflectionToStringBuilder< /a>.像这样的东西:
You could make use of ReflectionToStringBuilder. Something like:
我已经使用反射完成了几次。我有一个通用方法,本质上是
dumpObject
,它迭代字段并将它们放入字符串中。这非常有效,但如果您经常调用此函数,请务必考虑性能 - 最好对 tostring 进行硬编码。例如,I've done this a few times using reflection. I had a generic method that was essentially
dumpObject
that iterated through the fields and put them to a string. This works great, but be sure to consider performance if you're calling this often - it might be better to hard code the tostring. e.g.,