Created
March 17, 2017 18:49
-
-
Save kmerrell42/eb42d286ae2450ebd1c384cd571a48e6 to your computer and use it in GitHub Desktop.
Java NullObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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