问题描述
PHP有一个函数,它输出一个对象的内部内容,显示一个对象的类型和内容。
PHP has a var_dump() function which outputs the internal contents of an object, showing an object's type and content.
例如:
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);
将输出:
object(Person)#1 (2) {
["firstName:private"]=>
string(3) "Jon"
["lastName:private"]=>
string(5) "Smith"
}
什么是Java中的等价物会做同样的事情吗?
推荐答案
它不是很好在Java中,所以你不能免费获得它。它是通过约定而不是语言结构完成的。在所有数据传输类中(甚至可能在你编写的所有类中 ),你应该实现一个明智的方法。所以在这里你需要在 Person
类中覆盖 toString()
并返回所需的状态。
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.
,有助于编写一个好的toString方法,或者大多数IDE都有一个自动的 toString()
写入快捷方式。
There are utilities available that help with writing a good toString method, or most IDEs have an automatic toString()
writing shortcut.
编辑:链接已死 - 现已可用。
links dead - now available here
.
这篇关于什么是Java var_dump的Java等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!