简体   繁体   中英

Print POJO to System.out issue

Following some tutorial ( this one ) I am not getting same output on console. The tutorial is about converting Java object to/from XML using JAXB API - JAXBContext, Unmarshaller, Marshaller.

This is POJO code:

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;
    }

}

This is unmarshalling code:

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();
        }
    }

}

And this is ./jaxb-data/file.xml file content:

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

I am getting com.jaxb.example.Customer@15e8d410 when I run this class.

Question: Why am I not getting Customer [name=Some Name, age=33, id=1] on output?

You have to overwrite Customer#toString , which gets implicitly called when you Sysout an object. The standard implementation is the fully qualified class name and the hexcoded- hashcode() of this object.

You will need to override toString() method for meaningful reprsentation of your object. System.out.println() calls toString() method and you can see the string returned from toString() method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM