How to set Java Object into JaxBElement ?

How to set Java Object into JaxBElement ?
* In JaxBElement we are having setValue(T t) method. this will help us to solve this problem.
* java.xml.bind.JAXBElement.setValue()

Eg. Lets Use College Class as Bean. MainJaxBElement class as main class to process the College Class.
package com.javavirus.jaxbelement;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class College{
private int id;
private String name;

public College(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "College [id=" + id + ", name=" + name + "]";
}
}

package com.javavirus.jaxbelement;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
public class MainJaxBElement {

public static void main(String[] args) {
College college = new College (1001,"Loyola");
JAXBElement<College> jaxbElement =  new JAXBElement(new QName(College.class.getSimpleName()), College.class, null);
College finalValue;
if(!jaxbElement.isNil()){
finalValue = jaxbElement.getValue();
         System.out.println("finalValue => "+finalValue.toString()); 
      } else {
         jaxbElement.setValue(college);     
      }
finalValue = jaxbElement.getValue();\
      System.out.println("Result ==>:"+finalValue.toString()); 
   }
}

Comments

Post a Comment

Popular posts from this blog

GitLab