Skip to content

Instantly share code, notes, and snippets.

@DMCApps
Created January 18, 2017 02:27
Show Gist options
  • Save DMCApps/bd50e54c9aa0e6230ffbf205574dc0d0 to your computer and use it in GitHub Desktop.
Save DMCApps/bd50e54c9aa0e6230ffbf205574dc0d0 to your computer and use it in GitHub Desktop.
Utilities used to help with the interactions with POJO.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* Created by DMCApps
*
* Utilities used to help with the interactions with POJO.
*/
public final class ObjectUtils {
private static final String TAG = ObjectUtils.class.getSimpleName();
private ObjectUtils() {}
/**
* This is a seudo method of the C#/Swift as keyword.
* It will check the type of obj and cast to the appropriate class if it is that type or return null it not.
* This gives us a more defensive style of programming and performs the type casting in a single line.
* This replaces the notion of using
*
* <code>
* if (objX instanceof ClassY) {
* ClassY objY = (ClassY)objX;
* // continue code here
* }
* </code>
*
* Example use:
* <code>
* ClassY objY = ObjectUtil.as(objX, ClassY.class);
* if (objY == null) {
* // Handle null
* }
* // continue code here.
* </code>
*
* @param
* object -> The object to be checked with as
* @param
* asClass -> The class type we are checking object against
* @param
* <T> -> The type of class that we anticipate returning
* @return
* The object casted to the given class or<br />
* null if it's not that type of class
*/
public static <T> T as(Class<T> asClass, Object object) {
return asClass.isInstance(object) ? asClass.cast(object) : null;
}
/**
* This method makes a "deep clone" of a POJO object it is given.
* <a href="http://stackoverflow.com/a/6183597/845038">Deep Copy vs Shallow Copy</a>
*
* @param
* object -> Object to clone
* @return
* The cloned object.
* @throws IOException
* @throws ClassNotFoundException
*/
public static <T> T deepClone(Class<T> clazz, T object) throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
return as(clazz, ois.readObject());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment