打印java类中字段的所有值的最佳方法是什么
我有一个名为 Product 的类,其中包含一些字段。 我想打印产品对象的所有值。
Class Product{
String code;
String description;
}
Product p = new product();
p.setCode("C");
p.setDescription("desc");
我想打印产品实例的值,例如
Code:C Description:Desc.
我有大约 100 个类,所有类中都有很多字段。最好的方法是什么。
I have a class called Product with some fields.
I want to print all the values for a product object.
Class Product{
String code;
String description;
}
Product p = new product();
p.setCode("C");
p.setDescription("desc");
I want to print values of product instances ex
Code:C Description:Desc.
I have around 100 classes with lot of fields in all the classes.What is the best way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要重写 java.lang.Object 中的 toString() 方法。
如果您使用 Eclipse,您可以自动生成一个 toString 方法来执行您想要的操作。以下是如何执行此操作的一个很好的示例:
http://idiot2genius .wordpress.com/2011/05/17/eclipse-generate-java-tostring-method-quickly/
Apache Commons Lang 项目中有一个非常有用的类您可能也会发现有帮助:
http://commons.apache .org/lang/api-2.4/org/apache/commons/lang/builder/ToStringBuilder.html
You'll want to override the toString() method in java.lang.Object.
If you use Eclipse, you can autogenerate a toString method that does what you want. Here's a good example of how to do that:
http://idiot2genius.wordpress.com/2011/05/17/eclipse-generate-java-tostring-method-quickly/
There's a very useful class in the Apache Commons Lang project that you might find helpful as well:
http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/builder/ToStringBuilder.html
如果您不想手动构建字符串或手动管理更改,您可能会考虑类似 Commons Lang
ReflectionToStringBuilder.reflectionToString()
方法,也可通过ToStringBuilder
类使用。If you don't want to build the string by hand, or manage changes manually, you might consider something like the Commons Lang
ReflectionToStringBuilder.reflectionToString()
method, also available through theToStringBuilder
class.