Skip to content

Instantly share code, notes, and snippets.

@SangsooNam
Created June 18, 2016 13:57
Show Gist options
  • Save SangsooNam/dedbee8bb19dd8e6bd59f730444fcc61 to your computer and use it in GitHub Desktop.
Save SangsooNam/dedbee8bb19dd8e6bd59f730444fcc61 to your computer and use it in GitHub Desktop.
Create a dummy for listeners or callbacks
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