gpt4 book ai didi

java - 取决于类型、泛型、继承或两者的实例化?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:34:11 25 4
gpt4 key购买 nike

我有一个方法实例化了一个特定的类,这取决于作为此方法的参数发送的类型。这非常有效,但我真的不喜欢这种 if(c == class_name.class) 处理这个问题的方法,我很确定有更好的方法使用泛型和继承来做到这一点.我使用的方法在我看来(可能是错误的...)很脏。

我遵循了几个关于泛型和继承的教程,但即使我认为我或多或少地分别理解了这两个概念,我也在努力理解两者的混合......而且我认为这两个概念一旦混合就可以解决我的问题。任何人都可以告诉我遵循的正确轨道,泛型,继承,或者让我的代码保持这样。有更好的方法吗?

这是我的实际方法:

private void addData(String csvFile, char separator, Class<?> c) {
int lineNumber = 1;
CSVReader reader;

try {
reader = new CSVReader(new InputStreamReader(getAssets().open(csvFile)), separator);
String[] line;

realm.beginTransaction();
if(c == FlagDef.class) {
while ((line = reader.readNext()) != null) {
FlagDef flagDef = new FlagDef(Long.parseLong(line[0]), line[1], line[2]);
Log.d(TAG, String.format("%s %s %s", line[0], line[1], line[2]));
realm.copyToRealm(flagDef);
lineNumber++;
}
}
if(c == Picture.class) {
while ((line = reader.readNext()) != null) {
Picture picture = new Picture(Long.parseLong(line[0]), line[1]);
Log.d(TAG, String.format("%s %s", line[0], line[1]));
realm.copyToRealm(picture);
lineNumber++;
}
}
realm.commitTransaction();

reader.close();
} catch (FileNotFoundException ex) {
Log.e(TAG, String.format("File %s not found : %s", csvFile, ex));
} catch (IOException ex) {
Log.e(TAG, String.format("Error parsing line number %s : %s", lineNumber, ex));
}
}

调用此方法:

addData(FILE_FLAGS,SEPARATOR,FlagDef.class);
addData(FILE_PICTURES,SEPARATOR,Picture.class);

可以找到copyToRealm方法的声明here

这是针对 Android 的,我实际上是针对 API 16。

为了简洁起见,我在这里只指出了两种类型 PictureFlagDef,但我计划至少有 10 种不同的类型。

最佳答案

有类型删除的概念,在运行时,泛型将被删除。你现在拥有的被认为是“干净的”并且在这种情况下使用了很多。

我唯一可以建议的是让你的 PictureFlagDef 可以实现一个标记接口(interface),例如 CSVable(是的,真的坏名字)并将你的方法更改为:

<T extends CSV> void addData(Class<T> c)

这样你的类型在编译时就被过滤了(你只能传递一个实现了CSVable的对象)

关于java - 取决于类型、泛型、继承或两者的实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47594825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com