简体   繁体   English

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

[英]what is the best way to print all the values of the fields in a java class

I have a class called Product with some fields. 我有一个名为Product的类,其中包含一些字段。 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 我想打印产品实例ex的值

Code:C Description:Desc.

I have around 100 classes with lot of fields in all the classes.What is the best way. 我有大约100个班级,所有班级都有很多领域。什么是最好的方法?

You'll want to override the toString() method in java.lang.Object. 您将要覆盖java.lang.Object中的toString()方法。

If you use Eclipse, you can autogenerate a toString method that does what you want. 如果使用Eclipse,则可以自动生成执行所需功能的toString方法。 Here's a good example of how to do that: 这是一个很好的例子:

http://idiot2genius.wordpress.com/2011/05/17/eclipse-generate-java-tostring-method-quickly/ 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: Apache Commons Lang项目中有一个非常有用的类,您可能会发现也很有用:

http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/builder/ToStringBuilder.html http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/builder/ToStringBuilder.html

如果您不想手工构建字符串或手动管理更改,则可以考虑使用类似于Commons Lang ReflectionToStringBuilder.reflectionToString()方法的方法,该方法也可以通过ToStringBuilder类获得。

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

相关问题 打印Collection类的元素的最佳方法是什么? - What is the best way to print elements of a Collection class? 在java中打印多维数组的最佳方法是什么? - What is the best way to print a multidimensional array in java? 在java中按多个字段过滤的最佳方法是什么 - What is the best way of filtering by multiple fields in java 计算Java类的校验和的最佳方法是什么? - What is the best way to calculate a checksum for a Java class? 有没有办法通过netbeans代码模板打印Java类字段? - Is there a way to print java class fields by netbeans code templates? 在Java中将三维数组的所有值设置为零的最佳方法是什么? - What's the best way to set all values of a three-dimensional array to zero in Java? 使用 Java 8 将 2 个或多个字段组合为 Map 中的键的最佳方法是什么? - What is the best way to combine 2 or more fields as a Key in a Map, using Java 8? 将Java类转换为php类的最佳方法是什么? - what is the best way to transform a java Class into a php class? 从抽象类的所有子类调用方法的最佳方法是什么? - What is the best way to call methods from all the subclasses of an abstract class? 了解 Class 中的所有变量是否都是 null 的最佳方法是什么? - What is the best way to know if all the variables in a Class are null?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM