What is the Java equivalent of PHP var_dump?

I think that the best way to do It, is using google-gson (A Java library to convert JSON to Java objects and vice-versa)

Download It, add "jar" file to your project

HashMap<String, String> map = new HashMap<String, String>();

map.put("key_1", "Baku");
map.put("key_2", "Azerbaijan");
map.put("key_3", "Ali Mamedov");

Gson gson = new Gson();

System.out.println(gson.toJson(map));

Output:

{"key_3":"Ali Mamedov","key_2":"Azerbaijan","key_1":"Baku"}

You can convert any object (arrays, lists and etc) to JSON. I think, that It is the best analog of PHP's var_dump()


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.


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));
}

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.

Tags:

Php

Java