我正在编写一个调用方法的包装器,如果抛出异常,则记录它并返回默认值。
InvocationHandler invocationHandler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
return invokeOn(wrapped, method, args);
} catch (InvocationTargetException e) {
Throwable targetException = e.getTargetException();
if (targetException instanceof Exception) {
errorReporter.exception(wrapped, (Exception) targetException);
return defaultValueFor(method.getReturnType());
} else {
throw targetException;
}
}
}
};
我想找到一种实现defaultValueFor的好方法,以便为每种可能的类型返回一个很好的默认值 - 相当于
@SuppressWarnings("unchecked")
protected static <T> T defaultValueFor(Class<T> claz) {
if (claz == boolean.class)
return (T) Boolean.FALSE;
if (claz == short.class)
return (T) Short.valueOf((short) 0);
if (claz == int.class)
return (T) Integer.valueOf(0);
if (claz == long.class)
return (T) Long.valueOf(0);
...
return null;
}
这种代码必须在JMock等中,但是有没有比这个可怕的样板更好的实现?
答案 0 :(得分:4)
class DefaultValues {
static final Map<Class<?>,Object> defaultValues = new HashMap<Class<?>,Object>();
// load
static {
defaultValues.put(boolean.class, Boolean.FALSE);
defaultValues.put(byte.class, new Byte((byte)0));
defaultValues.put(short.class, new Short((short)0));
defaultValues.put(int.class, new Integer(0));
defaultValues.put(long.class, new Long(0L));
defaultValues.put(char.class, new Character('\0'));
defaultValues.put(float.class, new Float(0.0F));
defaultValues.put(double.class, new Double(0.0));
}
public static final <T> T defaultValueFor(Class<T> clazz) {
return (T)defaultValues.get(clazz);
}
}