我有以下方法
之前:
Employee getEmployee(String id){
String url = "http://localhost" + id;
//duplicate code
}
List<Employee> getEmployees(){
String url = "http://localhost";
//duplicate code
}
在上述两种方法中,我有重复的代码,我尝试过如下所示:
之后:
<T> T get(id){
//here duplicate code from above 2 methods
}
Employee getEmployee(String id){
return get(id);
}
List<Employee> getEmployees(){
return get(null);
}
我是泛型新手,如何解决上述重复问题?
最佳答案
乍一看,您似乎有以下选择:
- 如果您确定您的“重复代码”始终返回正确的类型,那么您可以随时进行转换(可能会导致运行时问题) 但这与泛型无关,返回类型不能依赖于 null 或 not
Employee getEmployee(String id){
return (Employee) get(id);
}
List<Employee> getEmployees(){
return (List<Employee>) get(null);
}
- 另一种选择是始终在方法get中返回List,并简单地在方法getEmployee中获取第一项(不要忘记检查它是否不为空以避免IndexOutOfBoundsException)
我相信还有更好的选择。您也可以分享被删除的部分,也许它可以改进。老实说,我担心它是否完全相同。
关于java - 如何使用java泛型删除重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60500591/