【发布时间】:2023-03-04 22:50:01
【问题描述】:
我创建了一个父类 Repo,它具有在列表中插入、删除、显示和删除对象的方法。 Repo 是一个泛型类。我为 Repo 创建了一个子类(如 DepartmentRepo 类)并传递了 Department、Employee 等类。我想对传递给 Repo 类的任何类对象执行插入、删除、显示和删除操作。 我需要从java中的Generic类获取方法“get”的返回值。我只能从 Generic 中获取方法名,这里我提到了代码文件
public class Department {
private long Id;
private String Name;
private String Location;
public Department() {
}
public Department(long id, String name, String location) {
super();
Id = id;
Name = name;
Location = location;
}
public long getId() {
return Id;
}
public void setId(long id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
}
import java.util.ArrayList;
import java.util.List;
public class Repo<T, U> {
List<T> list = new ArrayList<T>();
public List<T> getAll() {
return list;
}
public void insert(T obj) {
list.add(obj);
}
public T get(U id) throws NoSuchMethodException, SecurityException {
for (T ele : list) {
if (ele.getClass().getMethod("getId") == id) {
return ele;
}
}
return null;
}
public void delete(U id) throws NoSuchMethodException, SecurityException {
list.remove(get(id));
}
}
public class DepartmentRepo extends Repo<Department, Long>{
}
class MainApi
{
public static void main (String[] args)
{
DepartmentRepo dept = new DepartmentRepo ();
Department ict=new Department(10001,"Dept of ICT","Town");
Department cs=new Department(10002,"Dept of Computer Science","Pampaimadu");
Department bio=new Department(10003,"Dept of Bio Science","Pampaimadu");
Department sats=new Department(10004,"Dept of Statistics","Kurumankadu");
dept.insert(ict);
dept.insert(cs);
dept.insert(bio);
dept.insert(sats);
System.out.println();
dept.getAll();
try{
dept.get(10001);
}
catch(Exception e){
}
}
}
【问题讨论】:
-
你甚至没有使用你的 Repo 类,有什么问题? Department 类没有你调用的 get 方法
-
DepartmentRepo 使用的 Repo 类。你知道基本的继承和泛型吗?
-
错过了那节课。实际上,您需要做的就是创建具有这些类型的实例,无需为它创建(空)类。您知道自己隐藏了可能遇到的任何错误吗?
-
我的代码没有错误。 DepartmentRepo 不是一个空类。如果需要,我可以添加一些与部门相关的特定方法。
-
在您显示的代码中,您隐藏了异常。在您显示的代码中,DepartmentRepo 是空的。请记住,我们可以继续您显示的代码
标签: java generics inheritance