Showing posts with label Summary. Show all posts
Showing posts with label Summary. Show all posts

Thursday, 15 November 2012

Simon Sinek On Diffusion Of Innovation Summary

This post summarizes some of Simon Sinek's ideas about the diffusion of innovation, from a TED presentation.

Summary

  • Simon Sinek: People don't buy what you do, they buy why you do it
  • The goal is not to do business with everybody who needs what you have
  • The goal is to do business with people who believe what you believe
  • The part of the brain that controls decision does not control language
  • If people know why you do what you do, they can become loyal

Diffusion of Innovation
Diffusion of Innovation
  • Simon Sinek: You cannot reach mass market acceptance of an idea if you do not reach 15-18% of the market first, then the system tips
  • Early majority won't try something new before someone else tried it
  • The right people, right money and right market conditions do not guarantee success
  • Tivo told us what they had without you even ask it
  • Tivo could have said, if you want control on your TV (why), we have a product for you
  • People do not buy what you do, but why you do it
  • What you do only serves the proof of what customers believe in
  • Martin Luther King - 'I have a dream' speech, not 'I have a plan' speech
  • Leaders hold a position of power or authority, those who lead inspire us
  • We follow those who lead, not because we have to, but because we want to
  • We follow those who lead, not for them, but for ourselves
  • And it is those who start with why that have the ability to inspire those around them or find others who inspire them
P.S.: The reason I did not include Simon Sinek's golden circle is because I believe the why he created this circle is just an attempt to mystify people unnecessarily. He properly fails to apply his theory about selling his simplest idea. I don't buy it, which confirms his theory too...

Thursday, 9 August 2012

JAXB Annotation - XmlAdapter, Map, Special Types Annotations

Code examples are available from Github in the JAXB-JSON-XML-Marshalling directory.

How to use XmlAdapter and @XmlJavaTypeAdapter to handle Map in JAXB?

In situations where JAXB cannot handle unknown types, the solution is to create an XmlAdapter and use the @XmlJavaTypeAdapter in the class referring to the unknown type to indicate JAXB how to deal with it. A Java map is a good example.

We are going to illustrate this with an example. Assuming an object containing a generic map:
@XmlRootElement
public class ObjectWithGenericMap<K, V> {

    private Map<K,V> map;

    @XmlElement
    @XmlJavaTypeAdapter(JaxbMapAdaptor.class)
    public Map<K,V> getMap() {
        return map;
    }

    public void setMap(Map<K,V> map) {
        this.map = map;
    }

}
We are going to need an adaptor:
public class JaxbMapAdaptor<K, V>
        extends XmlAdapter<JaxbMapToList<K, V>, Map<K, V>> {

    @Override
    public Map<K, V> unmarshal(JaxbMapToList<K, V> v)
            throws Exception {
        HashMap<K, V> result = new HashMap<K, V>();
        for (JaxbMapToListEntry<K, V> jme : v.getList()) {
            result.put(jme.getKey(), jme.getValue());
        }
        return result;
    }

    @Override
    public JaxbMapToList marshal(Map<K, V> v) throws Exception {
        JaxbMapToList<K, V> result = new JaxbMapToList<K, V>();
        for (Map.Entry<K, V> entry : v.entrySet()) {
            JaxbMapToListEntry<K, V> jme = new JaxbMapToListEntry<K, V>();
            jme.setKey(entry.getKey());
            jme.setValue(entry.getValue());
            result.getList().add(jme);
        }
        return result;
    }

}

Basically, the above adaptor converts a map into a list of entries (with key and value) when marshalling, and converts this list of entries back into a HashMap when unmarshalling.

The map-to-list and corresponding entries are:
public class JaxbMapToList <K, V> {

    private List<JaxbMapToListEntry<K, V>> list
        = new ArrayList<JaxbMapToListEntry<K, V>>();

    public JaxbMapToList() {}

    public JaxbMapToList(Map<K, V> map) {
        for (Map.Entry<K, V> e : map.entrySet()) {
            list.add(new JaxbMapToListEntry<K, V>(e));
        }
    }

    public List<JaxbMapToListEntry<K, V>> getList() {
        return list;
    }

    public void setList(List<JaxbMapToListEntry<K, V>> entry) {
        this.list = entry;
    }

}

public class JaxbMapToListEntry<K, V> {

    private K key;
    private V value;

    public JaxbMapToListEntry() { }

    public JaxbMapToListEntry(Map.Entry<K, V> e) {
        key = e.getKey();
        value = e.getValue();
    }

    @XmlElement
    public K getKey() {
        return key;
    }

    public void setKey(K key) {
        this.key = key;
    }

    @XmlElement
    public V getValue() {
        return value;
    }

    public void setValue(V value) {
        this.value = value;
    }

}
Assuming one instantiates the object with generic map with destination and transports:
@XmlRootElement
public class Destination {

    private String destination;

    public String getDestination() {
        return destination;
    }

    @XmlElement
    public void setDestination(String dest) {
        this.destination = dest;
    }

}

@XmlRootElement
public class Transport {

    private String transport;

    public String getTransport() {
        return transport;
    }

    @XmlElement
    public void setTransport(String transp) {
        this.transport = transp;
    }

}

public static void main(String[] args) throws JAXBException {

    JAXBContext jaxbContext = JAXBContext.newInstance(
        ObjectWithGenericMap.class,
        Destination.class, Transport.class);

    ObjectWithGenericMap<Destination,Transport> owgm
        = new ObjectWithGenericMap<Destination,Transport>();

    Map<Destination,Transport> map
        = new HashMap<Destination,Transport>();
    owgm.setMap(map);

    Destination d = new Destination();
    d.setDestination("Paris");

    Transport t = new Transport();
    t.setTransport("Plane");

    map.put(d,t);

    d = new Destination();
    d.setDestination("New-York");

    t = new Transport();
    t.setTransport("Boat");

    map.put(d,t);

    ObjectWithGenericMap<Destination,Transport> retr
        = marshallingUnmarshalling(jaxbContext, owgm);

    for (Entry<Destination, Transport> e : retr.getMap().entrySet() ){
        Destination retrd = e.getKey();
        System.out.print(retrd.getDestination());
        Transport retrt = e.getValue();
        System.out.println(" " + retrt.getTransport());
    }

}
The generated XML and verification is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<objectWithGenericMap>
    <map>
        <list>
            <key xsi:type="destination" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <destination>New-York</destination>
            </key>
            <value xsi:type="transport" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <transport>Boat</transport>
            </value>
        </list>
        <list>
            <key xsi:type="destination" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <destination>Paris</destination>
            </key>
            <value xsi:type="transport" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <transport>Plane</transport>
            </value>
        </list>
    </map>
</objectWithGenericMap>
Paris Plane
New-York Boat

How to use: @XmlList, @XmlEnum, @XmlAttribute, @XmlValue, @XmlMimeType, @XmlInlineBinaryData?


To annotate an enum:
@XmlEnum
public enum MyEnum {

    @XmlEnumValue("v1")
    VAL_1,

    @XmlEnumValue("v2")
    VAL_2;

}
To specify the xml tag value and attributes:
@XmlAccessorType(XmlAccessType.FIELD)
public class SpecialItem {

    @XmlValue
    private String val;

    @XmlAttribute
    private String attribute1;

    @XmlAttribute
    private String attribute2;

    // Setter & Getters...

}
For remaining annotations and usage of the above:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class MultipleTypes {

    @XmlElement
    private MyEnum myEnum;

    @XmlElement
    @XmlList
    private List<String> data;

    @XmlElement
    private List<SpecialItem> specialItems;

    @XmlMimeType("image/jpeg")
    private Image image;

    @XmlInlineBinaryData
    private byte[] byteArray;

    // Setter & Getters...

}
The generated XML and verification is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<multipleTypes>
    <myEnum>v2</myEnum>
    <data>tre pml xng</data>
    <specialItems attribute2="ffff" attribute1="aaaa">pppp</specialItems>
    <specialItems attribute2="pqgd" attribute1="mer">xxw</specialItems>
    <image>/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAALABADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwCxBe6S1ha3ptg4MEYF29lGSXKA5JIznHvmuX1UaCmhapbwxW2023mxkWUSyedsbjPXaOTkdPX+9wieM/EEOlrpkeoEWS7SIfKQj5Rgfw88AflUb+JdVl0O7tHniMMkqbh9njDcq4Pzbcjj0PrXppRo3SuTVqVKrV7aH//Z</image>
    <byteArray>AQL9/A==</byteArray>
</multipleTypes>
pppp aaaa ffff
xxw mer pqgd
VAL_2
tre, pml, xng, 
1 2 -3 -4
Image is available: true

Remark

We have not covered all JAXB annotations, especially those related to XML schemas, but this tutorial should be enough to get one started and accomplish most objectives with JXTA.

JAXB to XMLJAXB to JSONJAXB Annotations Tutorial Table Of Content

Tuesday, 7 August 2012

JAXB Annotation - Can't Handle Interfaces

JAXB Can't Handle Interfaces in Generics

If you have a class with a List<Vehicle> and Vehicle is an interface, JAXB will throw an Exception at runtime:
my.package.MyInterface is an interface,
    and JAXB can't handle interfaces
The solution is to maket the interface an abstract class. For example:
public abstract class Vehicle {

    public abstract String getType();

}

@XmlRootElement
public class Bus extends Vehicle {

    private String type;

    public Bus() { };

    public Bus(String type) {
        this.type = type;
    }

    @XmlElement
    @Override
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}

@XmlRootElement
public class Car extends Vehicle {

    private String type;

    public Car() {};

    public Car(String type) {
        this.type = type;
    }
 
    @XmlElement
    @Override
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}

@XmlRootElement
public class ObjectWithListOfVehicles {

    private List<Vehicle> list;

    @XmlElementWrapper(name="MyVehicleList")
    @XmlElement
    public List<Vehicle> getList() {
        return list;
    }

    public void setList(List<Vehicle> list) {
        this.list = list;
    }

}
Assuming the following JAXB context:
public static void interfaceExamples() throws JAXBException {

    List<Vehicle> l = new ArrayList<Vehicle>();
    l.add(new Bus("Large bus"));
    l.add(new Bus("Small bus"));
    l.add(new Car("Ferrari"));

    // Object with generic list
    ObjectWithListOfVehicles owgl
        = new ObjectWithListOfVehicles();
    owgl.setList(l);

    JAXBContext jc = JAXBContext.newInstance(
        Bus.class, Car.class,
        ObjectWithListOfVehicles.class);

    ObjectWithListOfVehicles retr
        = marshallUnmarshall(owgl, jc);

    for (Vehicle s : retr.getList()) {
        System.out.println(
            s.getClass().getSimpleName()
            + " - " + s.getType());
    } System.out.println(" ");

}

public static <O> O marshallUnmarshall(O o, JAXBContext jc)
        throws JAXBException {

    // Creating a Marshaller
    Marshaller jaxbMarshaller = jc.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    StringWriter result = new StringWriter();
    jaxbMarshaller.marshal(o, result);

    // Printing XML
    String xml = result.toString();
    System.out.println(xml);

    // Creating an Unmarshaller
    Unmarshaller jaxbUnmarshaller = jc.createUnmarshaller();
    StringReader sr = new StringReader(xml);

    O retr = (O) jaxbUnmarshaller.unmarshal(sr);

    return retr;

}
The generated XML and verification is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<objectWithListOfVehicles>
    <MyVehicleList>
        <list xsi:type="bus" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <type>Large bus</type>
        </list>
        <list xsi:type="bus" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <type>Small bus</type>
        </list>
        <list xsi:type="car" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <type>Ferrari</type>
        </list>
    </MyVehicleList>
</objectWithListOfVehicles>

Bus - Large bus
Bus - Small bus
Car - Ferrari

Notice that JAXB is capable of recreating both Bus and Car instances.

Next

JAXB to XMLJAXB to JSONJAXB Annotations Tutorial Table Of Content

JAXB Annotation - JAXB Context, Generics

Understanding JAXB Context

In order to marshall and unmarshall JAXB annotated classes, one needs to create a JAXBContext. The instantiator method takes in a list of JAXB annotated Class.

By default, JAXB will include statically referenced classes in the list and inherited classes, but not transient or inheriting classes. The code examples are available from Github in the JAXB-JSON-XML-Marshalling directory.

Assuming:
@XmlRootElement
public class StaticallyReferenced {

    private String data;

    @XmlElement
    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
    
}

@XmlRootElement
public class StaticallyReferencedButTransient {
    
    private String data;

    @XmlElement
    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
    
}

@XmlRootElement
public class SomeA {
    
    private StaticallyReferenced sr;
    private StaticallyReferencedButTransient srbt;

    @XmlElement
    public StaticallyReferenced getSr() {
        return sr;
    }

    public void setSr(StaticallyReferenced sr) {
        this.sr = sr;
    }

    @XmlTransient
    public StaticallyReferencedButTransient getSrbt() {
        return srbt;
    }

    public void setSrbt(
            StaticallyReferencedButTransient srbt) {
        this.srbt = srbt;
    }

}

@XmlRootElement
public class InheritSomeA extends SomeA {
    
    private String moreData;

    @XmlElement
    public String getMoreData() {
        return moreData;
    }

    public void setMoreData(String moreData) {
        this.moreData = moreData;
    }
    
}
If one creates the following JAXB context:
JAXBContext jaxbContext =
    JAXBContext.newInstance(SomeA.class);
JAXB will only be able to process SomeA and StaticallyReferenced, not StaticallyReferencedButTransient or InheritSomeA.

How to use JAXB with Generics such as List, Set, etc...?

Assuming a simple example, where an object contains a List<String>:
@XmlRootElement
public class ObjectWithList {

    private List<String> list;

    @XmlElementWrapper(name="MyList")
    @XmlElement
    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

}
If the JAXB context is built as following (before a round trip):
public static void simpleExample() throws JAXBException {

    List<String> l = new ArrayList<String>();
    l.add("Somewhere");
    l.add("This and that");
    l.add("Something");

    // Object with list
    ObjectWithList owl = new ObjectWithList();
    owl.setList(l);

    JAXBContext jc = JAXBContext.newInstance(ObjectWithList.class);
    ObjectWithList retr = marshallUnmarshall(owl, jc);

    for (String s : retr.getList()) {
        System.out.println(s);
    } System.out.println(" ");

}
The generated XML with verification is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<objectWithList>
    <MyList>
        <list>Somewhere</list>
        <list>This and that</list>
        <list>Something</list>
    </MyList>
</objectWithList>

Somewhere
This and that
Something
A more sophisticated example with a generic list:
@XmlRootElement
public class ObjectWithGenericList<T> {

    private List<T> myList;

    @XmlElementWrapper(name="MyGenericList")
    @XmlElement
    public List<T> getList() {
        return myList;
    }

    public void setList(List<T> list) {
        this.myList = list;
    }

}
used with the following JAXB context and verification:
public static void genericListExample()
        throws JAXBException {

    List<Car> l = new ArrayList<Car>();
    l.add(new Car("red car"));
    l.add(new Car("blue car"));
    l.add(new Car("green car"));

    // Object with generic list
    ObjectWithGenericList<Car> owgl
        = new ObjectWithGenericList<Car>();
    owgl.setList(l);

    JAXBContext jc = JAXBContext.newInstance(
        ObjectWithGenericList.class, Car.class);
    ObjectWithGenericList<Car> retr
        = marshallUnmarshall(owgl, jc);

    for (Car s : retr.getList()) {
        System.out.println(
        s.getClass().getSimpleName() + " - " + s.getType());
    } System.out.println(" ");

}
generates the following XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<objectWithGenericList>
    <MyGenericList>
        <list xsi:type="car" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <type>red car</type>
        </list>
        <list xsi:type="car" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <type>blue car</type>
        </list>
        <list xsi:type="car" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <type>green car</type>
        </list>
    </MyGenericList>
</objectWithGenericList>

Car - red car
Car - blue car
Car - green car
Notice that JAXB is capable of recreating Car instances.

Next

JAXB to XMLJAXB to JSONJAXB Annotations Tutorial Table Of Content

Monday, 6 August 2012

JAXB Annotation - Basic Annotations, Inheritance

JAXB (Java Architecture for XML Binding) enables the mapping of Java object into XML documents back and forth. This post is an introduction, tutorial and summary of JAXB annotations. It proceeds with operational code examples to describe each feature.

The code examples are available from Github in the JAXB-JSON-XML-Marshalling directory. Most examples rely on the following piece of code to create XML files from annotated Java objects:
    public static void createXML(Object o) throws JAXBException {
        
        // Creating a Marshaller
        JAXBContext jaxbContext = JAXBContext.newInstance(o.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
 
        StringWriter result = new StringWriter();
        jaxbMarshaller.marshal(o, result);

        // Printing XML
        String xml = result.toString();
        System.out.println(xml);
        
    } 
In order to generate such XML documents, a JAXB context must be created. More details on this in part II.

@XmlRootElement

Defines the root element of the XML document. If not name is specified (like this for example: @XmlRootElement(name = "MyRootName"), the name of the element is taken from the class name.

This annotation can be used on a Class or on an enum. A Class does need a no parameter constructor or a factory method (more details in the @XmlType section).

For example:
@XmlRootElement(name="MyRootName")
public class A {

    private int a1 = 0;

    @XmlElement
    public int getA1() {
        return a1;
    }

    public void setA1(int a1) {
       this.a1 = a1;
    }

}
generates the following XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<MyRootName>
   <a1>28</a1>
</MyRootName>
One can also specify a namespace name for the XML element or a local name for the XML element.

Inheritance

When a class inherits of another annotated class, the root name is taken from the inheriting class:
@XmlRootElement
public class InheritsA extends A {

    private int b1 = 0;

    @XmlElement
    public int getB1() {
        return b1;
    }

    public void setB1(int b1) {
        this.b1 = b1;
    }

}
The generated XML is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<inheritsA>
    <a1>33</a1>
    <b1>66</b1>
</inheritsA>

@XmlElement / @XmlTransient

The @XmlElement indicates which element should be included in the XML conversion. If you want to annotate fields instead of getter methods, use the @XmlAccessorType(XmlAccessType.FIELD).

If you need to exclude a field from the generated XML, use the @XmlTransient annotation.
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class FieldAnnotation {

    @XmlElement
    private int a1 = 45;

    @XmlTransient
    private long a2 = 0;

    @XmlElement(nillable=true)
    private String xxx = null;

    @XmlElement(required=true)
    private String req;

    public int getA1() {
        return a1;
    }

    public void setA1(int a1) {
        this.a1 = a1;
    }

    public long getA2() {
        return a2;
    }

    public void setA2(long a2) {
        this.a2 = a2;
    }

    public String getXxx() {
        return xxx;
    }

    public void setXxx(String xxx) {
        this.xxx = xxx;
    }

    public String getReq() {
        return req;
    }

    public void setReq(String req) {
        this.req = req;
    }

} 
Assuming the following class creation:
FieldAnnotation fa = new FieldAnnotation();
fa.setA2(28);
fa.setReq("Some value");
generates:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<fieldAnnotation>
    <a1>45</a1>
    <xxx xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
    <req>Some value</req>
</fieldAnnotation>
One can also set a default string value, or set the XML Schema element name and the target namespace of the XML element via the @XmlElement annotation.

@XmlType

This annotation allows one to specify the order of items in the generated XML document. It can also be used to specify a factory class and/or a factory method (with no arguments) to create instances of the annotated class:
@XmlRootElement
@XmlType(propOrder={"a2", "a1"},
  factoryClass=OrderFactory.class,
  factoryMethod="myConstructor")
public class Order {

    private int a1 = 0;
    private int a2 = 0;

    @XmlElement
    public int getA1() {
        return a1;
    }

    public void setA1(int a1) {
        this.a1 = a1;
    }

    @XmlElement
    public int getA2() {
        return a2;
    }

    public void setA2(int a2) {
        this.a2 = a2;
    }

}
The factory class:
public class OrderFactory {
    public static Order myConstructor() {
        return new Order();
    }
}
The generated XML:
<order>
  <a2>99</a2>
  <a1>28</a1>
</order>
One can also set the XML Schema type and the target namespace of the XML Schema type with the @XmlType annotation.

@XmlSeeAlso

This annotation allows one to refer to other classes to include in the XML generation. In other words, if a referred class is not in the JAXB context, it will be taken into account anyway and won't trigger a runtime error. This annotation can be used as a safeguard when marshalling and unmarshalling.

This is best described with an example:
@XmlRootElement
public class Document {

    private String content = "";

    @XmlElement
    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}
@XmlRootElement
public class Image {

    private String name = "";

    @XmlElement
    public String getName() {
        return name;
    }

    public void setName(String content) {
        this.name = content;
    }

}
@XmlRootElement
@XmlSeeAlso({Document.class,Image.class})
public class Folder {

    private Document document = null;
    private Image image = null;

    @XmlElement
    public Document getDocument() {
        return document;
    }

    public void setDocument(Document document) {
        this.document = document;
    }

    @XmlElement
    public Image getImage() {
        return image;
    }

    public void setImage(Image image) {
        this.image = image;
    }

}
The generated output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<folder>
    <document>
        <content>My content</content>
    </document>
    <image>
        <name>My image</name>
    </image>
</folder>

Next

JAXB to XMLJAXB to JSONJAXB Annotations Tutorial Table Of Content

Tuesday, 31 July 2012

Java Number Formatting Summary

How to Add Leading Zero's to a Number?

To format a number with 10 digits (for example) and add leading 0 as necessary:
long l = 45294324;
String s = String.format("%010d", l);
System.out.println(s);
For multiple formatting in a same string:
String s2 = String.format("%03d-%05d", 45, 2);
System.out.println(s2);
The output is:

  0045294324
  045-00002

How to Perform Currency Formatting?

Java offers NumberFormat instances for specific Locales:
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(nf.format(445.34256));

nf = NumberFormat.getCurrencyInstance(Locale.JAPAN);
System.out.println(nf.format(445.34256));

nf = NumberFormat.getCurrencyInstance(Locale.GERMANY);
System.out.println(nf.format(445.34256));

The above code snippet produces the following:

  $445.34
  ¥445
  445,34 €

More about Java Internationalization here.

Java Generics IV - Incompatible Types, Reifed

How to Solve: "Uncompilable source code - incompatible types"?


The following piece of code:
public class MyClass {

  public static class A {};

  protected HashSet<A> theSet = new HashSet<A>();

  public Set<Object> getSet() {
    return (Set<? extends Object>) theSet;
  }

  public static void main(String[] args) {
    MyClass mc = new MyClass();
    Set<Object> s = mc.getSet();
  }

}
generates the following error at compile time:

  test3/MyClass.java:[13,15] incompatible types
  found   : java.util.Set<capture#128 of ? extends java.lang.Object>
  required: java.util.Set<java.lang.Object>

The HashSet<A> cannot be cast into a Set<Object>. One needs to create an new Set<Object> and copy the content of HashSet<A> to it:
public Set<Object> getSet() {

  Set<Object> result = new HashSet<Object>();
  result.addAll(theSet);
  
  return result;

  // return (Set<? extends Object>) theSet;

}

What Does Reified Mean in the Context of Java Generics?

It means that if you define a Set<String> and a Set<Integer>, Java does not (directly) provide the mean to retrieve the type used to instantiate the generics. In other words, it is not (easily) possible to retrieve String and Integer when inspecting the sets at runtime.


Part I  Part II   Part III   Part IV

Java Generics III - Array Initialization, Static Methods, Extend Class & Interfaces

How to Initialize an Array of Generic Type?

The following code will not compile:
public class A<V> {

  private Set<V>[] sets;

  public A(int size) {
     sets = new HashSet<V>[size];
  }

}
The solution is to use a cast:
     sets = (Set<V>[]) new HashSet[size];

How to Make a Static Method Generic?

The following code indicates how to proceed:
public class B<T> {

    // Allowed
    public static <U> U myStaticMethod(U u) {
        return ...;
    }

    // Not allowed
    public static T myStaticMethod2(T t) {
        return ...;
    }

}

How to Make a Generic Extends a Class and Multiple Interfaces?

This is a generic wildcard issue. Considering a class C, and two interfaces I1 and I2:
public class D<T extends C & I1 & I2> {
    
    // ...

}

The class must precede the interfaces. A generic can only extends one class at most.

Part I  Part II   Part III   Part IV

Monday, 30 July 2012

Java Generics II - Retrieving Type at Runtime

How to Retrieve the Type of a Generic at Runtime?

This is a very common question repeated over and over in forums and blogs. The answer is simple: it is impossible unless you use a workaround (or some kind reflexion, when possible, as we will see next).

In other words, there is no way you can achieve something like this:
public class MyQueue<T> extends PriorityQueue<T> {

    public boolean canTakeSuchElement(Object o) {
        return T.getClass().isInstance(o);
    }

}
Many have tried, nearly all failed (*). One workaround is the following:
public class MyQueue<T> extends PriorityQueue<T> {

    private Class<T> myElementType;

    public MyQueue(Class<T> elementType) {
        myElementType = elementType;
    }

    public boolean canTakeSuchElement(Object o) {
        return myElementType.isInstance(o);
    }

}

Which you can use as following:
MyQueue<String> mq = new MyQueue<String>(String.class);

if ( mq.canTakeSuchElement(333) ) {
    // No way...
} else if ( mq.canTakeSuchElement("azjsjdl") ) {
    // Ok...
}

Does Java Keep Any Trace of the Generic Instantiation Type at Runtime?

Contrary to the information commonly spread over the Internet, Java does keep some information at runtime about the types used to 'instantiate' generics. But it is not easy to retrieve it. See (*) and the next question.

How to Retrieve the Generic Type of a List, Set, Map... at Runtime?

It is possible using reflexion:
public class ExtractGenerics {

    public static class MyClass {

        List<String> l = new ArrayList<String>();
        Set<Integer> s = new HashSet<Integer>();
        Map<Double,String> m = new HashMap<Double,String>();

    }

    public static Class<?>[] extractGenericTypes(Field f) {

        ParameterizedType stringListType =
            (ParameterizedType) f.getGenericType();

        Type[] ata = stringListType.getActualTypeArguments();

        Class<?>[] result = new Class[ata.length];

        for (int i=0;i<ata.length;i++) {
            result[i] = (Class<?>) ata[i];
        }

        return result;

    }

    public static void printGenericTypes(Class<?>[] cs) {

        System.out.println("------");
        for ( Class c : cs ) {
            System.out.println(c);
        }
    }

    public static void main(String... args) throws Exception {

        printGenericTypes(
          extractGenericTypes(
            MyClass.class.getDeclaredField("l")));

        printGenericTypes(
          extractGenericTypes(
            MyClass.class.getDeclaredField("s")));

        printGenericTypes(
          extractGenericTypes(
            MyClass.class.getDeclaredField("m")));

    }

}

The above produces:

  ------
  class java.lang.String
  ------
  class java.lang.Integer
  ------
  class java.lang.Double
  class java.lang.String


(*) The concept of super token type has been introduced by Neil Gafter. It can be exploited via some complicated tricks to extract the Type (not a Class instance) used to 'instantiate' the generic type. Ian Robertson provides technical explanation here.

Although we won't develop it here, super token types can prove useful to create instances of the type used to 'instantiate' the generic type, when possible. If, with MyClass<T>, you create MyClass<List<String>>, you cannot instantiate a List<String>. However, if you create MyClass<ArrayList<String>>, you can instantiate ArrayList<String> (more on this in Neil Gafter's post mentioned earlier).

Yet, this solution does not cover well for constructors with parameters.


Part I  Part II   Part III   Part IV

Java Generics I - Erasure, Benefits

Using Java Generics can be tricky. New developers often have a hard time grasping the nuts and bolts of this feature. These posts summarize the most common pitfalls and caveats.

How Are Generics Compiled in Java?

Technically speaking, generics are not compiled into bytecode in Java. They are preprocessed by the compiler, before the Java code itself is compiled into bytecode. This process is called type erasure.

This is best described with an example:
Queue<String> q = new PriorityQueue<String>();
q.add("eeee");
String retr = q.element();

The above code in transformed into the following equivalent bytecode:
Queue q = new PriorityQueue();
q.add("eeee");
String retr = (String) q.element();

The value returned by q.element() is cast into a String.

What is the Benefit of Generics?

The main benefit is to check at compile time that all elements inserted or retrieved from the q object are strings, because after compilation, any element could technically be inserted in it. This could trigger unexpected errors, such as ClassCastException at runtime.

If some external code imported the q object defined in the above generic Java code, the compiler would check that this external code uses q properly. In others words, it would check that it only inserts or retrieves strings from it.

Like this, one is sure that bytecode won't throw ClassCastException at runtime. It also means that the generic code does not need to be recompiled, only the external code needs compilation.

By not introducing generics at the bytecode level, Java code written and compiled before generics were available can still use Java code using generics. The future is safe for code of the past.


Part I  Part II   Part III   Part IV