What is the Java equivalent of PHP var_dump?

后端 未结 11 609
北荒
北荒 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:13

    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.

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

    I use Jestr with reasonable results.

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

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

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

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

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

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