目标:我需要的是创建一个或多个函数来处理List
参数的不同类型,并且我将遍历函数中的列表。具有通用列表参数的函数? (超载函数)
尝试:用不同类型的列表
public static int update(List<MyClass> myClasses){};
public static int update(List<Project> rojects){};
public static int update(List<Time> times){};
由于与相同参数类型List
多种功能
1-多种功能但是,这被认为是在-编译为。
2-通用类型的列表,并使用(instanceof
)但是,我没有完全做到这一点,因为我不知道如何,以及像我读的那样,这似乎是这种行为的不利方式。
我的问题:实现这种需求的Java方法是什么?我需要一个干净的代码,我不在乎它是否复杂,我主要关心准确性和正确的编码。
PS:如果instanceof
的方法正确,那么请您提供一个关于如何迭代不同类型列表的示例。
感谢提前:)
编辑:不同的对象有相互没有关系,如,他们不相互延伸也不扩展超类。每个函数的块都会生成一个SQLite语句,这对每种类型都是不同的。
应对“恶劣的回答是:
所以最后我用你的建议组合,那就是实现与getClassType()
函数返回的类名的字符串一个基类,那么我会检查update(List<T> list)
函数中的返回值。
public static <T extends Item> int update(List<T> list){
...
// Loop through the list and call the update function
for (T item: list){
if (item.getClassType() == MyClass.CLASS_TYPE)
update((MyClass) item);
}
...
}
public interface Item {
/**
* @return Return the class type, which is the name of the class
*/
public String getClassType();
}
public class ClassProject implements Item{
public static final String CLASS_TYPE = "ClassProject";
@Override
public String getClassType() {
return CLASS_TYPE;
}
...
}
public class ClassTime implements Item{
public static final String CLASS_TYPE = "ClassTime";
@Override
public String getClassType() {
return CLASS_TYPE;
}
...
}
public class MyClass implements Item{
public static final String CLASS_TYPE = "MyClass";
@Override
public String getClassType() {
return CLASS_TYPE;
}
...
}
这样做的理由整个interface
是因为我不喜欢istanceof
并不能确定它的性能和成本,所以我试图让我自己的一个。现在是这样做的一个可怕的方式?
不同类型的处理块发生了什么?如果代码的类型A与类型B的列表相同,或者代码是通用的,并且不管列表中的基础类型是否更改。如果有两种可能的方法,这个答案将决定一个答案。 – cmbaxter
它会根据类型完全不同。该代码将为列表中的每个项目创建一个SQLite更新语句,并针对每种类型的项目创建不同的语句。 – LuckyMe