What is the Java equivalent of PHP var_dump?
Asked Answered
A

11

140

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');
var_dump($person);

will output:

object(Person)#1 (2) {
  ["firstName:private"]=>
  string(3) "Jon"
  ["lastName:private"]=>
  string(5) "Smith"
}

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

Avid answered 19/11, 2008 at 10:49 Comment(1)
have you tried db4o? it is not specifically for this, but I think will work perfectly;Cornejo
I
72

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.

Is answered 19/11, 2008 at 11:4 Comment(2)
commons.apache.org/lang/apidocs/org/apache/commons/lang/builder/…, this (maybe?): commons.apache.org/lang/api-2.5/org/apache/commons/lang/builder/…Sargent
See also #9445073 on Guava alternative and Intellij IDEA template.Improbability
D
31

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.

Daigle answered 19/11, 2008 at 15:56 Comment(4)
Yups, most PHP or Web Developer forget about debugging. Because they prefer to see the debug result in browser.Hydrophone
You can't use your IDE's debugger if, for example, you are programming your JSP code in Adobe Experience Manager's browser-based editor. :(Collapse
Maybe we can use it to test behaviour of your program in live environment by printing the vardump in html format.Posset
Sometimes, even when dealing with java, it is regrettably not possible or too much hassle to set up debugging.Adp
G
19

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()

Gonzalez answered 13/12, 2013 at 13:2 Comment(3)
Interesting... do you know why it is not a static method?Megdal
You can use It like a static method: new Gson().toJson(...) without creating a new variables.Gonzalez
Imo, it's better if you abstracted it into a custom utility class rather than use it directly, this gives you flexibility to manage third party dependenciesAureomycin
R
17

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));
}
Readjustment answered 19/11, 2008 at 11:6 Comment(2)
what's that Field you're using, imported from where?Baxie
java.lang.reflect.FieldReadjustment
P
8

The apache commons lang package provides such a class which can be used to build up a default toString() method using reflection to get the values of fields. Just have a look at this.

Protrusile answered 19/11, 2008 at 13:25 Comment(2)
updated link is commons.apache.org/lang/api-release/org/apache/commons/lang/…Starinsky
Both of those links are deadLeucoderma
D
6

I like to use GSON because it's often already a dependency of the type of projects I'm working on:

public static String getDump(Object o) {
    return new GsonBuilder().setPrettyPrinting().create().toJson(o);
}

Or substitute GSON for any other JSON library you use.

Doris answered 12/5, 2016 at 15:30 Comment(0)
N
3

I use Jestr with reasonable results.

Nonchalance answered 12/1, 2009 at 22:53 Comment(0)
P
2

I found this method to dump object, try this String dump(Object object)

Picaroon answered 18/9, 2013 at 9:28 Comment(0)
A
1

Just to addup on the Field solution (the setAccessible) so that you can access private variable of an object:

public static void dd(Object obj) throws IllegalArgumentException, IllegalAccessException {
    Field[] fields = obj.getClass().getDeclaredFields();
    for (int i=0; i<fields.length; i++)
    {
        fields[i].setAccessible(true);
        System.out.println(fields[i].getName() + " - " + fields[i].get(obj));
    } 

}
Amphibious answered 24/6, 2020 at 11:52 Comment(0)
T
0

I think something similar you could do is to create a simple method which prints the object you want to see. Something like this:

public static void dd(Object obj) { System.out.println(obj); }

It's not the same like var_dump(), but you can get an general idea of it, without the need to go to your debugger IDE.

Tauten answered 10/10, 2018 at 13:17 Comment(0)
R
-1

You XML serialization, and you should get a very neat representation even of deeply nested objects.

Ryswick answered 23/9, 2010 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.