[英]Decide cast and return type by Parameter
I really don't know what to look for and if this is even possible. 我真的不知道要寻找什么,如果可能的话。 I am trying to code a dynamic Fileloader. 我正在尝试编写动态Fileloader。
This is the code: 这是代码:
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;
}
What I want to do now is instead of creating a new method for every single object I want to use the 3rd argument (object or whatever) for the type casting. 我现在想做的是,而不是为每个要使用第3个参数(对象或其他对象)进行类型转换的对象创建新方法。
So I could write String myString = loadSerializable(this, test.dat, String)
or ArrayList<Fragment> = loadSerializable(this, test.dat, ArrayList<Fragment>)
and so on.... Help appreciated 所以我可以写String myString = loadSerializable(this, test.dat, String)
或ArrayList<Fragment> = loadSerializable(this, test.dat, ArrayList<Fragment>)
等等。
Something like 就像是
public static <T> T loadSerializable(Context context, String filename) {
// ...
T t = (T) readElement;
// ...
return t;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.