What is the Java equivalent of PHP var_dump?

后端 未结 11 608
北荒
北荒 2020-12-12 14:58

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

For example:

         


        
相关标签:
11条回答
  • 2020-12-12 15:01

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

    0 讨论(0)
  • 2020-12-12 15:03

    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.

    0 讨论(0)
  • 2020-12-12 15:03

    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));
    }
    
    0 讨论(0)
  • 2020-12-12 15:05

    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.

    0 讨论(0)
  • 2020-12-12 15:09

    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.

    0 讨论(0)
  • 2020-12-12 15:12

    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.

    0 讨论(0)
提交回复
热议问题