我如何从int到泛型类型整数投?整数、类型、int、到泛型

2023-09-04 06:44:37 作者:错过了某些错过°

我是比较新的Java和我习惯了在C#泛型等等都挣扎了一下这个code。基本上我希望通过按键得到一个存储的Andr​​oid preference一个通用的方法,并且此code,虽然难看,适用于布尔,但不是一个整数,当它吹了一个ClassCastException。谁能告诉我,为什么这是错的,也许帮我提高整个程序(使用通配符?)?

I'm relatively new to Java and am used to generics in C# so have struggled a bit with this code. Basically I want a generic method for getting a stored Android preference by key and this code, albeit ugly, works for a Boolean but not an Integer, when it blows up with a ClassCastException. Can anyone tell me why this is wrong and maybe help me improve the whole routine (using wildcards?)?

    public static <T> T getPreference(Class<T> argType, String prefKey, T defaultValue,
        SharedPreferences sharedPreferences) {

    ...

    try {
        if (argType == Boolean.class) {
            Boolean def = (Boolean) defaultValue;
            return argType.cast(sharedPreferences.getBoolean(prefKey, def));
        } else if (argType == Integer.class) {
            Integer def = (Integer) defaultValue;
            return argType.cast(new Integer(sharedPreferences.getInt(prefKey, def)));
        } else {
            AppGlobal.logWarning("getPreference: Unknown type '%s' for preference '%s'. Returning default value.",
                    argType.getName(), prefKey);
            return defaultValue;
        }
    } catch (ClassCastException e) {
        AppGlobal.logError("Cast exception when reading pref %s. Using default value.", prefKey);
        return defaultValue;
    }
}

我的呼唤code是:

My calling code is:

        mAccuracy = GlobalPreferences.getPreference(Integer.class, prefKey, mAccuracy, sharedPreferences);

下面是Android $ C $下调用getInt():

Here is the Android code for getInt():

public int getInt(String key, int defValue) {
        synchronized (this) {
            Integer v = (Integer)mMap.get(key);
            return v != null ? v : defValue;
        }
    }

我已经试过各种方法 - 使用本地INT,铸造到一个整数,但没有任何工程

I've tried various ways - using the native int, casting to an Integer, but nothing works.

推荐答案

原来的preference我试图读取存储为一个字符串,所以投异常是从内部的Andr​​oid code到来不是我的。感谢您的帮助。但因为我是一个Java的新手,如果你觉得有什么一般不对我的家常便饭,请教我更好的办法。

It turns out the preference I'm trying to read is stored as a string so the cast exception is coming from inside the Android code not mine. Thanks for your help. But as I am a Java-newbie, if you think there is anything generally wrong with my routine, please teach me a better way.