How do I cast from int to generic type Integer?

前端 未结 3 1408
猫巷女王i
猫巷女王i 2021-01-27 12:48

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 ke

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-27 13:02

    Try defining a bunch of functions with the same name that take a different type for the default, and let the compiler figure it out. Java really ties your hands when working with types, especially primitive types.

    public function int getPreference( String key , int missing ) { return sharedPreferences.getInt( key , missing ); }
    public function boolean getPreference( String key , boolean missing ) { return sharedPreferences.getBoolean( key , missing ); }
    public function String getPreference( String key , String missing ) { return sharedPreferences.getString( key , missing ); }
    

    Edit:

    If you are trying to get an object (not primitive) regardless of the type, you can use:

    public function Object getPreference( String key , Object missing ) { return sharedpreferences.contains( key ) ? sharedPreferences.getAll().get( key ) : missing; }
    

    If you are trying to get a specific type like int regardless of what is stored, you can use:

    public function int getPreference( String key , int missing ) {
        int result = missing;
        Object value = sharedpreferences.contains( key ) ? sharedPreferences.getAll().get( key ) : null;
        if ( value instanceof Integer ) result = ((Integer)value).intValue();
        if ( value instanceof Boolean ) result = ((Boolean)value).booleanValue() ? 1 : 0;
        // repeat for every other primitive wrapper type you care about
        return result;
    }
    

    If you are trying to get a result only if it is a certain type, you can use something like:

    public function Object getPreference( Class inRequire , String key , Object missing ) {
        Object value = sharedpreferences.contains( key ) ? sharedPreferences.getAll().get( key ) : null;
        if ( !( value instanceof inRequire ) ) {
            value = null;
        }
        return ( value == null ) ? missing : value;
    }
    

提交回复
热议问题