打印自定义对象可以通过以下几种方式实现:
public class CustomObject {
private String name;
private int age;
// 构造方法、getter和setter方法省略
@Override
public String toString() {
return "CustomObject [name=" + name + ", age=" + age + "]";
}
}
public class Main {
public static void main(String[] args) {
CustomObject obj = new CustomObject("John", 25);
System.out.println(obj.toString());
}
}
import com.fasterxml.jackson.databind.ObjectMapper;
public class CustomObject {
private String name;
private int age;
// 构造方法、getter和setter方法省略
public String toJsonString() {
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(this);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
public class Main {
public static void main(String[] args) {
CustomObject obj = new CustomObject("John", 25);
System.out.println(obj.toJsonString());
}
}
import java.lang.reflect.Field;
public class CustomObject {
private String name;
private int age;
// 构造方法、getter和setter方法省略
public void printObject() {
Class<?> clazz = this.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
System.out.println(field.getName() + ": " + field.get(this));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
CustomObject obj = new CustomObject("John", 25);
obj.printObject();
}
}
以上是三种常见的打印自定义对象的方法,根据实际需求选择适合的方式。
领取专属 10元无门槛券
手把手带您无忧上云