简体   繁体   English

Java泛型编译失败

[英]Java compilation failed for generics

public <T> void saveData(String key, T value) {

        SharedPreferences.Editor editor =  sharedPreferences.edit();

        if (value instanceof String) {
            editor.putString(key, (String) value);
        } else if (value instanceof Boolean) {
            editor.putBoolean(key, (boolean) value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (int) value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (float) value);
        } else if (value instanceof Long) {
            editor.putLong(key, (long) value);
        } else {
            System.out.println("Unknown type");
        }

        editor.apply();
    }

When I am building the project then I am getting error as 当我构建项目时,我得到了如下错误

error: incompatible types: T cannot be converted to boolean
where T is a type-variable:
T extends Object declared in method <T>saveData(String,T)

This error is coming for long, int and float as well. 这个错误将持续很长时间,int和float也是如此。

The error is only for primitive types, so pay attention on using primiteves instead of Objects. 该错误仅适用于原始类型,因此请注意使用原始对象而不是对象。 Generics work with objects. 泛型与对象一起工作。

Another way to achieve this with no if at all, so cyclomatic complexity 0: 实现此目标的另一种方法, if根本没有, if cyclomatic complexity 0:

blic void caller(){
    SharedPreferences.Editor editor = sharedPreferences.edit();
    saveDate(editor, "key-string", "string value");
    saveDate(editor, "key-boolean", true);
    saveDate(editor, "key-integer", 7);
    saveDate(editor, "key-float", 7.0f);
    saveDate(editor, "key-long", 7L);
    editor.apply();
}


public void saveData(Editor editor, String key, String value) {
    editor.putString(key, (String) value);
}

public void saveData(Editor editor, String key, Boolean value) {
    editor.putBoolean(key, (boolean) value);
}

public void saveData(Editor editor, String key, Integer value) {
    editor.putInt(key, (int) value);
}
public void saveData(Editor editor, String key, Float value) {
    editor.putFloat(key, (float) value);
}
public void saveData(Editor editor, String key, Long value) {
    editor.putLong(key, (long) value);
}

This way you pay the penalty in number of rows which is higher. 这样,您将以较高的行数来支付罚款。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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