viernes, 31 de marzo de 2017

How to generate a Method with Generic Classes in Java?

Wellcome again,

Today I'm going to explain how to generate methods with generic classes in the call in Java.

First of all, I'm going to show you an example:

        public <T> T convertirDesdeXml(Class<T> c, byte[] xml) {
XStream xStream = new XStream();
xStream.alias(c.getSimpleName(), c);
T objecte = (T)xStream.fromXML(new String(xml));
return objecte;
}

This example converts an xml in byte[] format to a generic object.

We have to use a placeholder that is presented with <T> syntax. A placeholder is a String name that represents any object type that you will use in the context (the class, a method, an static call, etc.).

The placeholder <T> indicates that you can use the class T like a generic type in the method.

You can complicate the call like <T extends java.util,Map>. This new example indicates that the placeholder T extends the interface Map or, what is the same, the operator instanceof returns true.

You can complicate the call like <T, K>. In this example you use two placeholder and you can you the number of placeholder you want.

With the placeholder you have your first generic method with generic classes.

Thanks for the read!

Try it and have fun!