Skip to content

Instantly share code, notes, and snippets.

@kmerrell42
Created March 17, 2017 18:49
Show Gist options
  • Save kmerrell42/eb42d286ae2450ebd1c384cd571a48e6 to your computer and use it in GitHub Desktop.
Save kmerrell42/eb42d286ae2450ebd1c384cd571a48e6 to your computer and use it in GitHub Desktop.
Java NullObject
public class NullObject {
private static class NullInvocationHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Class<?> returnType = method.getReturnType();
if (returnType == Byte.TYPE || returnType == Short.TYPE || returnType == Integer.TYPE ||
returnType == Long.TYPE || returnType == Float.TYPE || returnType == Double.TYPE ||
returnType == Character.TYPE) {
return 0;
} else if (returnType == Boolean.TYPE) {
return false;
} else {
return null;
}
}
}
public static <T> T create(Class<T> nullObjClazz) {
Object proxy = Proxy.newProxyInstance(nullObjClazz.getClassLoader(), new Class<?>[]{nullObjClazz}, new NullInvocationHandler());
return nullObjClazz.cast(proxy);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment