打印java类中字段的所有值的最佳方法是什么

发布于 2024-12-17 02:04:33 字数 312 浏览 3 评论 0原文

我有一个名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

两相知 2024-12-24 02:04:33

您需要重写 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

£烟消云散 2024-12-24 02:04:33

如果您不想手动构建字符串或手动管理更改,您可能会考虑类似 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 the ToStringBuilder class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文