Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

public class Main {
    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Parent.class, IntegerChild.class, StringChild.class);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        IntegerChild integerChild = new IntegerChild();
        integerChild.getItem().add(1);
        integerChild.getItem().add(2);
        marshaller.marshal(integerChild, System.out);

        StringChild stringChild = new StringChild();
        stringChild.getItem().add("A");
        stringChild.getItem().add("B");
        marshaller.marshal(stringChild, System.out);
    }

    @XmlRootElement
    public static class Parent<T> {

        private List<T> item = new ArrayList<T>();

        @XmlTransient
        public List<T> getItem() {
            return item;
        }

        public void setItem(List<T> item) {
            this.item = item;
        }

    }

    @XmlRootElement
    public static class StringChild extends Parent<String> {

        @Override
        @XmlElement
        public List<String> getItem() {
            return super.getItem();
        }

        @Override
        public void setItem(List<String> item) {
            super.setItem(item);
        }

    }

    @XmlRootElement
    public static class IntegerChild extends Parent<Integer> {

        @Override
        @XmlElement
        public List<Integer> getItem() {
            return super.getItem();
        }

        @Override
        public void setItem(List<Integer> item) {
            super.setItem(item);
        }

    }
}