通过参数确定强制转换和返回类型

时间:2014-02-13 22:08:00

标签: java android

我真的不知道该寻找什么,如果这是可能的话。我正在尝试编写动态Fileloader。

这是代码:

public static Serializable loadSerializable(Context context,
        String filename, Object object) {
    final String DEBUGTAG = "Loading data" ;
    Serializable serializable = null;
    ObjectInputStream oin = null;
    try {
        File file = new File(context.getFilesDir(), filename);
        FileInputStream in = new FileInputStream(file);
        oin = new ObjectInputStream(in);
        Object readElement = oin.readObject();
        serializable = (Serializable) readElement; // here I want dynamic casting
        Log.d(DEBUGTAG, "Success : " + filename);
    } catch (FileNotFoundException e) {
        Log.d(DEBUGTAG, "File not found");
    } catch (StreamCorruptedException e) {
        Log.d(DEBUGTAG, "Stream Corrupted");
    } catch (IOException e) {
        Log.d(DEBUGTAG, "IOException");
    } catch (ClassNotFoundException e) {
        Log.d(DEBUGTAG, "Class not Found");
    } catch (NullPointerException e) {
        Log.d(DEBUGTAG, "NullPointer - File does not exist yet");
    } finally {
        if (oin != null)
            try {
                oin.close();
            } catch (IOException e) {
                Log.d(DEBUGTAG, "IOException - Stream not closed");
            }
    }
    return serializable;
}

我现在要做的不是为每个我想要使用第三个参数(对象或其他)进行类型转换的对象创建一个新方法。

所以我可以写 String myString = loadSerializable(this, test.dat, String)ArrayList<Fragment> = loadSerializable(this, test.dat, ArrayList<Fragment>)等等...... 帮助赞赏

1 个答案:

答案 0 :(得分:0)

这样的东西
public static <T> T loadSerializable(Context context, String filename) {
    // ...
    T t = (T) readElement;
    // ...
    return t;
}