简体   繁体   中英

How can I obtain the default value for a type in Java?

I'm writing a wrapper that calls a method, and if an exception is thrown, logs it and returns a default value.

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;
            }
        }
    }
};

I'd like to find a nice way of implementing defaultValueFor so that it returns a good default value for each possible type - the equivalent of

@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;
}

This sort of code must be in JMock etc, but is there a nicer implementation than this horrible boiler-plate?

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);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM