2
我正在寫一個調用方法的包裝器,如果引發異常,則記錄它並返回一個默認值。如何獲取Java中某個類型的默認值?
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的但有沒有比這個可怕的鍋爐板更好的實施?
你不需要clazz.cast(defaultValues.get(clazz))嗎? – laz 2011-03-16 16:47:19
我想只有布爾,char,short,byte,int,long,float和double的條目,之後我可以返回null,但我仍然希望更優雅的東西;-) – 2011-03-16 16:51:22
我能夠無需轉換即可運行代碼。 – corsiKa 2011-03-16 16:51:41