Created
June 18, 2016 13:57
-
-
Save SangsooNam/dedbee8bb19dd8e6bd59f730444fcc61 to your computer and use it in GitHub Desktop.
Create a dummy for listeners or callbacks
This file contains hidden or 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
import com.google.common.base.Defaults; | |
import com.google.common.primitives.Primitives; | |
import java.lang.reflect.Array; | |
import java.lang.reflect.InvocationHandler; | |
import java.lang.reflect.Method; | |
import java.lang.reflect.Proxy; | |
public final class Dummy { | |
private Dummy() {} | |
@SuppressWarnings("unchecked") | |
public static <T> T of(Class<T> type) { | |
return (T) Proxy.newProxyInstance( | |
type.getClassLoader(), | |
new Class<?>[]{type}, | |
new InvocationHandler() { | |
@Override | |
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | |
final Class<?> returnType = Primitives.unwrap(method.getReturnType()); | |
if (returnType.isPrimitive()) { | |
return Defaults.defaultValue(returnType); | |
} else if (returnType.isArray()) { | |
return Array.newInstance(returnType.getComponentType(), 0); | |
} else { | |
return null; | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment