Java:print_r?

Jea*_*lea 18 java data-structures

上次我问这里如何填充数据结构.现在我想知道Java中是否存在某些东西,比如我在PHP中使用的print_r,它代表我在地图和列表中填充的内容而不必自己编写算法.

有任何想法吗?

wor*_*ad3 10

在集合上调用toString应该返回一个包含所有元素字符串表示的字符串.

但这不适用于内置数组,因为它们没有toString覆盖,只会给你一个内存地址.

  • @trusktr对于自定义类,你必须覆盖`toString()`方法,使它返回你想要的. (2认同)

dar*_*pet 9

java中的toString()和PHP中的print_r()之间确实存在差异.请注意,php中也有__toString(),相当于java中的toString(),所以这不是答案.

当我们有一个对象结构时,就会使用print_r,我们很快就会看到对象的完整图形及其值.

在java中为每个对象实现toString无法与print_r进行比较.

而是使用gson.它与print_r完成相同的工作

Gson gson = new GsonBuilder().setPrettyPrinting().create();
的System.out.println(gson.toJson(someObject));

这样,您不需要为测试它所需的每个对象实现toString.

以下是文档:http: //sites.google.com/site/gson/gson-user-guide

演示类(在java中):

公共类A {

int firstParameter = 0;
B secondObject = new B();
Run Code Online (Sandbox Code Playgroud)

}

公共课B {

String myName = "this is my name";  
Run Code Online (Sandbox Code Playgroud)

}

这是php中的print_r输出:

对象
(
[firstParameter:private] => 0
[secondObject:private] => B对象
(
[myName:private] =>这是我的名字
)

)

这是java中带gson的输出:

{
"firstParameter":0,
"secondObject":{
"myName":"这是我的名字"
}
}


laz*_*laz 8

根据您的具体要求,解决方案可能非常简单.以下内容不会生成print_r提供的格式化输出,但它允许您输出列表,数组和映射的结构:

    // Output a list
    final List<String> list = new ArrayList<String>();
    list.add("one");
    list.add("two");
    list.add("three");
    list.add("four");
    System.out.println(list);

    // Output an array
    final String[] array = {"four", "three", "two", "one"};
    System.out.println(Arrays.asList(array));

    // Output a map
    final Map<String, String> map = new HashMap<String, String>();
    map.put("one", "value");
    map.put("two", "value");
    map.put("three", "value");
    System.out.println(map.entrySet());
Run Code Online (Sandbox Code Playgroud)

对于其他类型的对象,您可以使用反射为此目的创建实用程序.


小智 7

您可以尝试使用旧的Apache Commons Lang的ToStringBuilder.