尝试在 Java 项目中实现泛型和继承类。 出于这个原因,我创建了将继承所有特定类和接口(interface)的“基”类和接口(interface)。
我的意思是,我有一个基本接口(interface)
public interface BaseServices<T> {
public boolean validate(T item, int id) throws Exception;
}
以及该接口(interface)的基本实现
public class BaseServicesImpl implements BaseServices<BaseBO> {
@Autowired
BaseDao dao;
CategoryBO bo;
public BaseServicesImpl()
{
this.bo = new CategoryBO();
}
@Override
public boolean validate(BaseBO item, int id) throws Exception {
return dao.validate("name",item.toString(), id);
}
}
其中 BaseBO 是所有其他对象将扩展的业务对象。
然后,对于一个特定的对象,我将有一个扩展基础接口(interface)的特定接口(interface)。
public interface CategoryServices extends BaseServices {
}
及其实现:
public class CategoryServicesImpl extends BaseServicesImpl implements CategoryServices<CategoryBO> {
@Autowired
CategoryDao categoryDao;
public CategoryServicesImpl()
{
this.dao = categoryDao;
}
@Override
public boolean validate(CategoryBO item, int id) throws Exception {
return dao.validate("name",item.getName(), id);
}
}
某些对象可以实现通用“Validate”方法(仅验证名称)或将其扩展到类所需的地方public class CategoryServicesImpl extends BaseServicesImpl implements CategoryServices。
我怎样才能使这项工作?可能吗?我正在尽我所能重用我的代码。让我知道是否有其他方法。
编辑: 我想做的是拥有一个基类,其中包含所有类的所有通用方法,比方说,创建、编辑、删除、获取、getAll 等的基础。然后在每个类中我也可以拥有并覆盖这些方法,因为在某些类中它们会有所不同,但在大多数情况下,它们只会做同样的事情,因此它将调用基类中定义的通用方法。
最佳答案
只需进行一些更改,您就可以轻松实现您想要的效果:
public interface BaseServices<T extends BaseBO> {
boolean validate(T item, int id) throws Exception;
}
public interface CategoryServices
extends BaseServices<CategoryBO> {
}
public class BaseServicesImpl<T extends BaseBO>
implements BaseServices<T> {
@Override
public boolean validate(T item, int id) throws Exception {
return true;
}
}
public class CategoryServicesImpl
extends BaseServicesImpl<CategoryBO>
implements CategoryServices {
@Override
public boolean validate(CategoryBO item, int id) throws Exception {
return true;
}
}
关键是让您的通用 T
类型成为 BaseBO
的后代,然后将您的 BaseServicesImpl
类调整为通用的。
关于java - 实现通用接口(interface)和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35144268/