java - 实现通用接口(interface)和继承

标签 java object generics inheritance

尝试在 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/

相关文章:

c# - 界面中发生了什么?

java - 通过 POST 将 BitMap 对象(和一些其他字符串)发送到服务器

java - android - 菜单项未显示在操作栏中

java - Java 中奇怪的对象/类行为

javascript - 如何按parentId JS对对象数组进行排序

.net - List<T> 如何在内部映射?

java - 在运行时插入不同的对象,泛型 JAVA

java - 每个 Namedcache 的 Coherence 分布式缓存过期

java - logback 中的 MaxBackupIndex

PHP 对象生命周期