Java:print_r?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/148204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:56:04  来源:igfitidea点击:

Java: print_r?

javadata-structures

提问by Jean Paul Galea

last time I asked how to populate a data structure here. Now I would like to know if there's something in Java, like the print_rI use in PHP, to represent what I have populated in the Maps and lists without having to do my own algorithm.

上次我问如何在这里填充数据结构。现在我想知道 Java 中是否有一些东西,比如我在 PHP 中使用的print_r,来表示我在地图和列表中填充的内容,而无需执行我自己的算法。

Any ideas?

有任何想法吗?

采纳答案by workmad3

Calling toString on the collection should return a string containing all the elements string representations.

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

This won't work with built-in arrays though, as they don't have a toString override and will just give you a memory address.

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

回答by Daniel Hiller

I don't know of an equivalent of print_r in java.

我不知道 java 中的 print_r 等价物。

But...

但...

Every object has a default implementation of the toString() method, the list and map implementations print their contents if you call toString() for them.

每个对象都有一个 toString() 方法的默认实现,如果您为它们调用 toString() ,则列表和映射实现会打印它们的内容。

If you need any debug information printed out, toString() may be the place you are looking for.

如果您需要打印出任何调试信息, toString() 可能是您正在寻找的地方。

回答by Tim Mooney

You might try the good old Apache Commons Lang's ToStringBuilder.

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

回答by DeeCee

There is no equivalent for print_r in Java.

Java 中没有 print_r 的等价物。

But for maps or lists you can use the foreach-loop like this:

但是对于地图或列表,您可以像这样使用 foreach 循环:

List <String> list = …; // fills your list 

// print each list element 

for (String s : list) {

   System.out.println(s);

 }

回答by Hans-Peter St?rr

For arrays the easiest way is Arrays.asList(array).toString() . I generally implement toString() on objects I like to habe in debug outputs. For generated objects (JAXB etc.) though might need to make an utility class to print it.

对于数组,最简单的方法是 Arrays.asList(array).toString() 。我通常在调试输出中喜欢的对象上实现 toString() 。对于生成的对象(JAXB 等),虽然可能需要创建一个实用程序类来打印它。

回答by jm4

Others have mentioned the toString()method. This is really only useful when the object implements toString(). If it has not been implemented properly you will end up with something like this: java.lang.Object@1b9240e.

其他人提到了这个toString()方法。这实际上仅在对象实现toString(). 如果一直没有执行正确,你将最终是这样的:java.lang.Object@1b9240e

Even if it is a little tedious it is still easy to implement toString()in your own classes, but third party classes will not always implement it. You are much better off using a debugger. The only reason things like print_reven exist in PHP is because of the lack of a real debugger. I think you will find that being able to set breakpoints instead of using a bunch of diagnostic print statements will result in a much faster workflow and cleaner code.

即使它有点乏味,toString()在您自己的类中仍然很容易实现,但第三方类不会总是实现它。最好使用调试器。print_rPHP 中甚至存在这样的东西的唯一原因是缺乏真正的调试器。我认为您会发现能够设置断点而不是使用一堆诊断打印语句将导致更快的工作流程和更清晰的代码。

回答by laz

Depending on exactly what you want to do, the solution could be fairly simple. The following won't produce the formatted output that print_r provides, but it will allow you to output the structure of lists, arrays, and maps:

根据您想要做什么,解决方案可能相当简单。以下不会产生 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());

For other types of objects you could use reflectionto create a utilityfor this purpose.

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

回答by darpet

There is really difference between toString() in java and print_r() in PHP. Note that there is also __toString() in php which is equivalent to toString() in java, so this is not really the answer.

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

print_r is used when we have a structure of objects and we like quickly to see the complete graph of objects with their values.

当我们有一个对象结构并且我们喜欢快速查看对象及其值的完整图形时,将使用 print_r。

Implementing toString in java for each object has not the power to compare with print_r.

在java中为每个对象实现toString并没有和print_r相提并论的能力。

Instead use gson. It does the same job as print_r

而是使用 gson。它与 print_r 做同样的工作

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

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

In this way you do not need to implement toString for every object you need to test it.

通过这种方式,您无需为需要测试的每个对象都实现 toString。

Here is the documentation: http://sites.google.com/site/gson/gson-user-guide

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

Demo classes (in java):

演示类(在 Java 中):

public class A {

int firstParameter = 0;
B secondObject = new B();

}

public class B {

String myName = "this is my name";  

}

公共类 A {

int firstParameter = 0;
B secondObject = new B();

}

公共类 B {

String myName = "this is my name";  

}

Here is the output in php with print_r:

这是带有print_r的php输出:

Object
(
[firstParameter:private] => 0
[secondObject:private] => B Object
(
[myName:private] => this is my name
)

)

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

)

Here is the output in java with gson:

这是带有gson的java输出:

{
"firstParameter": 0,
"secondObject": {
"myName": "this is my name"
}
}

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

回答by stivlo

My take for a Java print_rlike functionality, is the class RecursiveDumpthat I wrote. It's not perfect, but it is working well for me. The usage is:

我对类似 Java 的print_r功能的看法是我编写的RecursiveDump类。它并不完美,但对我来说效果很好。用法是:

String output = RecursiveDump.dump(...);

It could be improved using generics, I wrote it many years ago, before I knew about them. Also while it tries to deal with some Collection types, with Objects it will just call the toString()method.

它可以使用泛型来改进,我多年前写的,在我知道它们之前。此外,当它尝试处理一些 Collection 类型时,它只会调用 ObjectstoString()方法。

I thought to use Reflection to extract field names for classes without a proper toString(), but since Spring Roo@RooToStringcan write the toString()method for you...

我想使用反射来提取没有正确的类的字段名称toString(),但是由于Spring Roo @RooToString可以toString()为您编写方法......

Of course the alternative is to use the inspector tool of a debugger, but sometimes is quicker to use prints.

当然,另一种方法是使用调试器的检查器工具,但有时使用打印会更快。