将POJO打印到System.out问题

时间:2014-05-20 12:30:40

标签: java jaxb

遵循一些教程(this one)我在控制台上没有获得相同的输出。 本教程是关于使用JAXB API将Java对象转换为XML或从XML转换 - JAXBContext,Unmarshaller,Marshaller。

这是POJO代码:

package com.jaxb.example;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    private String name;
    private int age;
    private int id;

    public String getName() {
        return name;
    }
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }
    public int getId() {
        return id;
    }
    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}

这是解组代码:

package com.jaxb.example;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class JAXBExampleTestUnmarshall {

    public static void main(String [] args){

        try {
            File file = new File("./jaxb-data/file.xml");

            JAXBContext context = JAXBContext.newInstance(Customer.class);
            Unmarshaller jaxbUnmarshaller = context.createUnmarshaller();

            Customer customer = (Customer)jaxbUnmarshaller.unmarshal(file);
            //System.out.println(customer.getId());
            //System.out.println(customer.getName());
            //System.out.println(customer.getAge());
            System.out.println(customer);

        } catch (JAXBException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

}

这是./jaxb-data/file.xml文件内容:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="1">
    <age>33</age>
    <name>Some Name</name>
</customer>

我在上课时得到com.jaxb.example.Customer@15e8d410

问题:为什么我的输出没有Customer [name=Some Name, age=33, id=1]

2 个答案:

答案 0 :(得分:3)

您必须覆盖Customer#toString,当您对某个对象进行Sysout时会隐式调用该hashcode()。标准实现是完全限定的类名和此对象的十六进制编码 - {{1}}。

答案 1 :(得分:1)

您需要覆盖toString()方法才能有意义地表示对象。 System.out.println()调用toString()方法,您可以看到从toString()方法返回的字符串。

public String toString(){
   return "Customer [name =" + name+ ", age=" + age
            + ",id =" + id "]";
 }