What is the Java equivalent of PHP var_dump?

04/09/2020 19:00:01

PHP has a var_dump() function which outputs the internal contents of an object, showing an object's type and content.

For example:

class Person {
  private $firstName;
  private $lastName;

  public function __construct($firstName, $lastName) {
    $this->firstName = $firstName;
    $this->lastName = $lastName;

$person = new Person('Jon', 'Smith');

will output:

object(Person)#1 (2) {
  string(3) "Jon"
  string(5) "Smith"

What is the equivalent in Java that will do the same?

Verified Answer (65 Votes)

11/19/2008 16:04:20

It is not quite as baked-in in Java, so you don't get this for free. It is done with convention rather than language constructs. In all data transfer classes (and maybe even in all classes you write...), you should implement a sensible toString method. So here you need to override toString() in your Person class and return the desired state.

There are utilities available that help with writing a good toString method, or most IDEs have an automatic toString() writing shortcut.


Answer #2 (31 Votes)

11/19/2008 20:56:22

In my experience, var_dump is typically used for debugging PHP in place of a step-though debugger. In Java, you can of course use your IDE's debugger to see a visual representation of an object's contents.


Answer #3 (18 Votes)

11/19/2008 16:06:04

Your alternatives are to override the toString() method of your object to output its contents in a way that you like, or to use reflection to inspect the object (in a way similar to what debuggers do).

The advantage of using reflection is that you won't need to modify your individual objects to be "analysable", but there is added complexity and if you need nested object support you'll have to write that.

This code will list the fields and their values for an Object "o"

Field[] fields = o.getClass().getDeclaredFields();
for (int i=0; i<fields.length; i++)
    System.out.println(fields[i].getName() + " - " + fields[i].get(o));
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.