MyUserObject.java - Create Object from Data Type Class

Q

How to create data objects from data type classes generated from the JAXB XJC tool? I have the User.java generated from User.xsd.

✍: FYIcenter.com

A

If you have the User.java class generated as in the previous tutorial, you can follow this tutorial to create User data objects in your XML application.

1. Enter the following Java code, MyUserObject.java, in the .\src\ folder:

// Copyright (c) FYIcenter.com
import com.fyicenter.demo.User;
import com.fyicenter.demo.ObjectFactory;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class MyUserObject {
   public static void main(String[] args) throws Exception {
      XMLGregorianCalendar d = DatatypeFactory.newInstance()
         .newXMLGregorianCalendarDate(1970, 1, 1, 1);

      ObjectFactory f = new ObjectFactory();
      User u = f.createUser();
      u.setName("Frank Y. Ivy");
	  u.setBirthDate(d);
	  u.setSex("Male");
      u.setID(101);

	  System.out.println("My user object:");
	  System.out.println("   Name: "+u.getName());
	  System.out.println("   BirthDate: "+u.getBirthDate());
	  System.out.println("   Sex: "+u.getSex());
	  System.out.println("   ID: "+u.getID());
   }
}

2. Compile and run MyUserObject.java as shown below. The compiler will automatically compile the User.java code under the same .\src\ folder:

\fyicenter>cd src

\fyicenter\src>\local\jdk-1.8.0\bin\javac MyUserObject.java

\fyicenter\src>\local\jdk-1.8.0\bin\java MyUserObject
My user object:
   Name: Frank Y. Ivy
   BirthDate: 1970-01-01+00:01
   Sex: Male
   ID: 101

 

Examples for JAXB (Java Architecture for XML Binding)

⇒⇒FAQ for jaxb-*.jar - Java Architecture for XML Binding

2018-05-08, 350👍, 0💬