打印对对象的引用

打印对对象的引用

本文介绍了打印对对象的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手.说,我有一个个人类.我要打印

I am a newbie in java. Say, I have a class Individual. I want to print

Individual ind = new Individual();
System.out.println(ind);

上面的代码给出如下输出:

Above code gives output like this:

Individual@1922221
  1. 这有什么意义?
  2. 是某种独特的ID为了那个对象?
  3. 我可以自定义它吗?我的意思是写一个函数我自己的,在打印时会输出?
  4. 如果是这样,我该怎么办这个吗?

推荐答案

如果要打印任何对象的有意义的内容,则必须实现自己的 toString()方法,该方法将覆盖parent( Object )类的 toString()方法.默认情况下,所有类(无论您创建什么)都扩展 Object 类.

If you want to print meaningful content of any object, you have to implement your own toString() method, which will override the parent(Object) class's toString() method. By default all the classes(Whatever you create) extends Object class.

示例代码:

public class Individual {
    private String name;
    private String city;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Name of Individual :").append(this.getName())
                .append("\nCity :").append(this.getCity());
        return builder.toString();
    }
    public static void main(String[] args) {
        Individual individual = new Individual();
        individual.setName("Crucified Soul");
        individual.setCity("City of Crucified Soul");
        System.out.println(individual);
    }
}

输出:

Name of Individual :Crucified Soul
City :City of Crucified Soul

如果您的类较大且包含许多变量,则可以使用 XStream 来实现toString() 方法.XStream将以XML格式打印有意义的对象.即使您可以将它们解析回等效的对象.希望这会对您有所帮助.

If you have bigger class with many variables, you can use XStream to implement your toString() method. XStream will print your object meaningful in XML format. Even you can parse them back to equivalent object. Hope this would help you.

这篇关于打印对对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 15:55